Java ArrayList Clear

Use the clear method on an ArrayList. An ArrayList can be cleared and reused for faster performance.
ArrayList, clear. Often in programs we add elements to an ArrayList, and then must add elements to a new, separate ArrayList. Sometimes we can reuse the ArrayList.ArrayList
Allocation performance in Java is excellent. But if we reuse the same ArrayList many times, we can reduce the burden on the garbage collector and speed things up.
Example benchmark. Consider this benchmark program. It has two main loops. It tests the performance of adding 100 elements to an ArrayList from java.util.

Version 1: An "outer" ArrayList is used. It is cleared on each iteration of the for-loop. Only one is allocated.


Version 2: An "inner" ArrayList is used, and it is allocated on each iteration of the benchmark (with "new ArrayList").

Result: When we reuse the same ArrayList, we get much better performance. The memory is left allocated after a clear() call.

Java program that benchmarks ArrayList, clear import java.util.ArrayList; public class Program { public static void main(String[] args) { ArrayList<Integer> outer = new ArrayList<>(); long t1 = System.currentTimeMillis(); // Version 1: reuse and clear same ArrayList. for (int i = 0; i < 1000000; i++) { outer.clear(); for (int x = 0; x < 100; x++) { outer.add(x); } if (outer.get(0) != 0) { return; } } long t2 = System.currentTimeMillis(); // Version 2: allocate ArrayList many times. for (int i = 0; i < 1000000; i++) { ArrayList<Integer> temp = new ArrayList<>(); for (int x = 0; x < 100; x++) { temp.add(x); } if (temp.get(0) != 0) { return; } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 226 ms clear() 639 ms new ArrayList
For popular algorithms, including parsers, we add data to collections and then clear them repeatedly. This benchmark establishes that reusing an ArrayList is best.
A summary. When possible, try to reuse the same ArrayList. Be sure to call clear() on it when this is needed. Reducing allocations appears to improve Java runtime performance significantly.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls