Created
February 11, 2020 04:41
-
-
Save wingadium1/db78cc601cd6c9baaab08cbb2ff791dc to your computer and use it in GitHub Desktop.
Benchmark Vector and ArrayList using JMH
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
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Vector; | |
import org.openjdk.jmh.annotations.Benchmark; | |
import org.openjdk.jmh.profile.GCProfiler; | |
import org.openjdk.jmh.profile.StackProfiler; | |
import org.openjdk.jmh.runner.Runner; | |
import org.openjdk.jmh.runner.RunnerException; | |
import org.openjdk.jmh.runner.options.Options; | |
import org.openjdk.jmh.runner.options.OptionsBuilder; | |
import java.util.Arrays; | |
public class BenchmarkJMH { | |
static Integer[] ints = new Integer[0]; | |
static { | |
final List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); | |
for (int i = 0; i < 5; i++) | |
list.addAll(list); | |
ints = list.toArray(ints); | |
} | |
static List<Integer> intList = Arrays.asList(ints); | |
static Vector<Integer> vec = new Vector<Integer>(intList); | |
static List<Integer> list = new ArrayList<Integer>(intList); | |
@Benchmark | |
public Vector<Integer> testVectorAdd() { | |
final Vector<Integer> v = new Vector<Integer>(); | |
for (Integer i : ints) | |
v.add(i); | |
return v; | |
} | |
@Benchmark | |
public long testVectorTraverse() { | |
long sum = (long) Math.random() * 10; | |
for (int i = 0; i < vec.size(); i++) | |
sum += vec.get(i); | |
return sum; | |
} | |
@Benchmark | |
public List<Integer> testArrayListAdd() { | |
final List<Integer> l = new ArrayList<Integer>(); | |
for (Integer i : ints) | |
l.add(i); | |
return l; | |
} | |
@Benchmark | |
public long testArrayListTraverse() { | |
long sum = (long) Math.random() * 10; | |
for (int i = 0; i < list.size(); i++) | |
sum += list.get(i); | |
return sum; | |
} | |
public static void main(String[] args) throws RunnerException { | |
Options opt = new OptionsBuilder().include(BenchmarkJMH.class.getSimpleName()).forks(1).build(); | |
new Runner(opt).run(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment