Skip to content

Instantly share code, notes, and snippets.

@sorokod
Last active August 27, 2016 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorokod/992d843389d2fc519bec to your computer and use it in GitHub Desktop.
Save sorokod/992d843389d2fc519bec to your computer and use it in GitHub Desktop.
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