I want to make a benchmark measuring insertion time into List, comparing ArrayList and LinkedList and using different initial size. So I created a benchmark using JMH for these targets:
@Warmup(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)
@Fork(value = 3, jvmArgsAppend = {"-XX:+UseParallelGC", "-Xms1g", "-Xmx1g"})
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class ListBench {
@Param({"100", "1000", "10000", "100000"})
int size;
@Param({"arraylist", "linkedlist"})
String type;
private List<Item> target;
private Item insert;
@Setup
public void setup() {
this.target = switch (this.type) {
case "arraylist" -> new ArrayList<>();
case "linkedlist" -> new LinkedList<>();
default -> {
throw new IllegalStateException(String.format("target is `%s`", this.target));
}
};
IntStream.range(0, this.size).mapToObj(Item::new).forEach(this.target::add);
this.insert = new Item(-1);
}
@Benchmark
public void insertFirst() {
this.target.add(0, this.insert);
}
@Benchmark
public void insertMiddle() {
this.target.add(this.size / 2, this.insert);
}
@Benchmark
public void insertLast() {
this.target.add(this.insert);
}
static class Item {
private final int val;
Item(final int val) {
this.val = val;
}
// + equals and hashCode
}
}
The problem with this benchmark is that it shares a state between iteration, so having initial size 100 it calls insertFirst many times and increases target's size. I'm looked at @Setup(Level.Invocation) to initialize target before each invokation, but the warnings in javadocs says that it's not suitable for my case:
This level is only usable for benchmarks taking more than a millisecond per single {@link Benchmark} method invocation. It is a good idea to validate the impact for your case on ad-hoc basis as well.
Each insertion takes less than a millisecond, and it'll be faster than setup.
What can I do with JMH to measure only add call on different targets and sizes using targets of same size per invokation?