clear() impl in Java's LinkedList
Their method ensures that even if other code still holds references to particular nodes, the other nodes will be GC'ed.
Otherwise, even a single external reference to one of the nodes would prevent the entire chain from being collected.
Also, other operations in the list might be going on simultaneously (e.g. views through subList()
or Collections.unmodifiableList()
, iterators), and this ensures that those things perceive the list as "empty" immediately.
IIRC, this was a change made in JDK6 to assist performance of certain (generational) GC algorithms. Often, the List
itself and older nodes will be in an older generation than some of the other nodes. The younger generations will get collected more frequently, with the result that young nodes get copied about before it is discovered that all the nodes are garbage.
So it's a minor performance optimisation. Memory performance optimisation is a little odd in that often it's not the code which is causing the problem that is taking the additional time to execute.