list.clear() vs list = new ArrayList<Integer>();

Greg picture Greg · Aug 5, 2011 · Viewed 146.7k times · Source

Which one of the 2 options is better and faster to clear an ArrayList, and why?

list.clear() 

or

list = new ArrayList<Integer>();

It happens that I have to, at random times, clear all entries from my ArrayList and I have no way to know how many new entries there will be in the future, there might be 0 or a 1000. Which method is faster and better, and why?

Answer

dfb picture dfb · Aug 5, 2011

It's hard to know without a benchmark, but if you have lots of items in your ArrayList and the average size is lower, it might be faster to make a new ArrayList.

http://www.docjar.com/html/api/java/util/ArrayList.java.html

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}