Question

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java#473

public void clear() {
    modCount++;

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

    size = 0;
}

My question is, why did they have to do an cycle through the backing array { O(n) } to make each element eligible for garbage collection when they could just have reinitialized the backing array, discarding references to the entire array as a whole { O(1) } and making it eligible for garbage collection? O(n) performance for clear() doesn't seem so nice to me or am I missing something?

Was it helpful?

Solution

Doing it the way they did lets you reuse the array without re-allocating its backing storage. If you wanted to reallocate the array, you could have done it yourself, since the representation of ArrayList mostly consists of its backing storage.

If they released the array as a whole, there would be very little difference between calling clear() and re-assigning the ArrayList itself. Now they give you an option to choose between reusing the array or replacing it with a brand-new one.

OTHER TIPS

This implementation allows array reuse without reallocation. Allocating an array in java can be O(n) anyway because the JVM will initialize all the elements to default values.

If you're clear()ing an ArrayList, you obviously intend to reuse it - and so any reuse may well have the same number of objects in it. So avoiding resize operations seems like a good idea.

Also, bare in mind that JIT compilation matters here, potentially a lot - that loop is going to be extremely cache friendly & the individual operations are very cheap - probably just a single machine instruction for each in the compiled case.

It is the same reason as clear() impl in Java's LinkedList which is the Java Generational Garbage Collection.

This ArrayList and the backing array are more likely to be promoted to the 'old generation' where it is possible for it to hold on to objects referenced by the array indexes that are more likely to be in the young generation. Setting all of the indexes to null allows those younger objects to be collected before the backing array is collected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top