Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Compare the performance of traversing LinkedList and ArrayList
package benchmark;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import java.util.*;
/**
* Run with:
* <code>
* mvn clean install
* java -jar target/benchmarks.jar ListsBenchmark -wi 10 -i 10 -f 1
* </code>
* @author David Soroko
*/
@State(Scope.Thread)
public class ListsBenchmark {
int N = 1000;
String[] array;
LinkedList<String> linkedList;
ArrayList<String> arrayList;
@Setup(Level.Trial)
public void setUp() {
array = new String[N];
linkedList = new LinkedList<>();
arrayList = new ArrayList<>();
for (int i = 0; i < N; i++) {
String uuid = UUID.randomUUID().toString();
linkedList.add(uuid);
arrayList.add(uuid);
}
}
@Benchmark
public void forArray(Blackhole bh) {
for (int i = 0; i < N; i++) {
bh.consume(array[i]);
}
}
@Benchmark
public void iteratorLinkedList(Blackhole bh) {
iterate(linkedList, bh);
}
@Benchmark
public void iteratorArrayList(Blackhole bh) {
iterate(arrayList, bh);
}
@Benchmark
public void forLinkedList(Blackhole bh) {
iterateFor(linkedList, bh);
}
@Benchmark
public void forArrayList(Blackhole bh) {
iterateFor(arrayList, bh);
}
private void iterateFor(List list, Blackhole bh) {
for (int i = 0; i < N; i++) {
bh.consume(list.get(i));
}
}
private void iterate(List list, Blackhole bh) {
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
bh.consume(iter.next());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment