Home
Java
ArrayList Clear
This page was last reviewed on Nov 25, 2022.
Dot Net Perls
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.
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.
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()); } }
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.
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); } }
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.