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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 17, 2025 (edit).