Java ArrayList Clear

Use the clear method on an ArrayList. An ArrayList can be cleared and reused for 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. Here is an example of the ArrayList clear method. We add 2 strings to the String ArrayList containing the names of animals. Then we clear it, and its size() drops to 0.Strings
Java program that uses ArrayList clear import java.util.ArrayList; public class Program { public static void main(String[] args) { ArrayList<String> animals = new ArrayList<>(); animals.add("bird"); animals.add("cat"); System.out.println("SIZE: " + animals.size()); // Call clear. animals.clear(); System.out.println("SIZE: " + animals.size()); } } Output SIZE: 2 SIZE: 0
Benchmark, clear. 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: It is faster to reuse the same ArrayList. 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. 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 program speed.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls