I'm setting up the JMH benchmarks for my application and I'm wondering is there any difference between passing JMH state via benchmark's and accessing it from benchmark body?
In other words
@Benchmark
public int myBenchmark(MyState state) {
MyObject objFromState= state.objFromState;
return objFromState.benchmarkMe();
}
VS
@Benchmark
public int myBenchmark() {
return objFromState.benchmarkMe();
}
From official JMH samples:
... Since JMH is heavily used to build concurrent benchmarks, we opted for an explicit notion of state-bearing objects ... Benchmark methods can reference the states, and JMH will inject the appropriate states while calling these methods.
All samples I saw always reference a state the same way as in the snippet:
@State(Scope.Thread)
public static class ThreadState {
volatile double x = Math.PI;
}
@Benchmark
public void measureUnshared(ThreadState state) {
state.x++;
}
You have to specify the scope of your state, explicitly declare it using annotation - you "register" it by doing this. The state object further will be injected to a method refers to it (by declaring the dependency as a method parameter). In your second snippet you reference to the state
object - yes, but this is not a shared state.