Skip to content

Instantly share code, notes, and snippets.

@wingadium1
Created February 11, 2020 04:41
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 wingadium1/5314b8f7884eff57649807a42fb786cc to your computer and use it in GitHub Desktop.
Save wingadium1/5314b8f7884eff57649807a42fb786cc to your computer and use it in GitHub Desktop.
Benchmark Vector and ArrayList using JMH
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