Last active
August 27, 2016 11:56
-
-
Save sorokod/992d843389d2fc519bec to your computer and use it in GitHub Desktop.
Compare the performance of traversing LinkedList and ArrayList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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