Restore Java List state after each benchmark in JMH

Viewed 145

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?

1 Answers

You should pass your State as a parameter to each benchmark, also to avoid dead code elimination, you should pass a Blackhole or return the value in each benchmark method. As reference to better understand, see the following snippet:

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class MyBenchmark {

    @State(Scope.Benchmark)
    public static class ArrayListState {

        @Param({"100", "1000", "10000", "100000"})
        int size;

        private List<Item> target = new ArrayList<>();
    }

    @State(Scope.Benchmark)
    public static class LinkedListState {

        @Param({"100", "1000", "10000", "100000"})
        int size;

        private List<Item> target = new LinkedList<>();
    }

    @Benchmark
    public void arrayListBenchmark(ArrayListState state, Blackhole blackhole) {
        for (int i = 0; i < state.size; i++) {
            state.target.add(new Item(-1));
        }
        // rest of the code to be measured
        blackhole.consume(state);
    }

    @Benchmark
    public void linkedListBenchmark(LinkedListState state, Blackhole blackhole) {
        for (int i = 0; i < state.size; i++) {
            state.target.add(new Item(-1));
        }
        // rest of the code to be measured
        
        blackhole.consume(state);
    }


    static class Item {

        private final int val;

        Item(final int val) {
            this.val = val;
        }

        // + equals and hashCode
    }

}
Related