C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
Version 1: An "outer" ArrayList is used. It is cleared on each iteration of the for-loop. Only one is allocated.
ForVersion 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