Skip to content

Instantly share code, notes, and snippets.

@wchargin
Created January 18, 2016 18:20
Show Gist options
  • Save wchargin/8b6b9782a918f4745dce to your computer and use it in GitHub Desktop.
Save wchargin/8b6b9782a918f4745dce to your computer and use it in GitHub Desktop.
ArrayList vs. LinkedList
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
public class ListsBenchmark {
private static final int UPTO = 1 << 24;
private static final Object ELEMENT = new Object();
private static final int TRIALS_WARMUP = 5;
private static final int TRIALS_REAL = 10;
private static long runBenchmarkFor(Supplier<List<Object>> creator) {
List<Object> target = creator.get();
long start = System.nanoTime();
for (int i = 0; i < UPTO; i++) {
target.add(ELEMENT);
}
Iterator<Object> it = target.iterator();
while (it.hasNext()) {
it.next();
}
long end = System.nanoTime();
return end - start;
}
private static class BenchmarkCase {
public final String name;
public final Supplier<List<Object>> producer;
public BenchmarkCase(String name, Supplier<List<Object>> impl) {
super();
this.name = name;
this.producer = impl;
}
}
public static void main(String[] args) {
final List<BenchmarkCase> impls = Arrays.asList(
new BenchmarkCase("ArrayList", ArrayList::new),
new BenchmarkCase("LinkedList", LinkedList::new));
System.out.print("Warming up the JVM");
for (int i = 0; i < TRIALS_WARMUP; i++) {
for (BenchmarkCase impl : impls) {
runBenchmarkFor(impl.producer);
}
System.out.print(".");
System.out.flush();
}
System.out.println();
final Map<BenchmarkCase, Long> results = new HashMap<>();
System.out.println("Running trials: ");
for (int i = 1; i <= TRIALS_REAL; i++) {
for (BenchmarkCase impl : impls) {
results.merge(impl, runBenchmarkFor(impl.producer),
(a, b) -> a + b);
System.gc();
}
System.out.print(i);
System.out.print(" ");
System.out.flush();
}
System.out.println();
System.out.println();
System.out.println("Results (total time):");
for (Map.Entry<BenchmarkCase, Long> result : results.entrySet()) {
long time = result.getValue();
System.out.format("%s: %d ns (%.03f s)%n", result.getKey().name,
time, time / 1e9);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment