Sub topic 3
Constant Folding and Trustworthy JMH Results
This chapter assumes basic Java, Maven, annotations, and the idea that the JVM compiles frequently used code at runtime.
Constant Folding
Constant folding is a compiler optimization that calculates an expression once when its inputs are known constants. For example, the JIT might replace Math.log(Math.PI) with one precomputed value. A benchmark can then measure almost no work.
Keep inputs in mutable state prepared outside the measured method. Return the result, or pass it to Blackhole, so the JIT cannot remove the computation.
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
@State(Scope.Thread)
public class FoldingBenchmark {
private double x;
@Setup
public void setup() {
x = Double.parseDouble("3.141592653589793");
}
@Benchmark
public double returned() {
return Math.log(x);
}
@Benchmark
public void consumed(Blackhole blackhole) {
blackhole.consume(Math.log(x));
}
}Warmup, Measurement, and Forks
JMH runs warmup iterations before recording measurements. This lets the JVM load classes and compile hot methods. Measurement iterations record the benchmark after warmup. A fork runs the benchmark in a separate JVM process, reducing interference between tests.
java -jar target/benchmarks.jar FoldingBenchmark \
-wi 3 -i 5 -f 2The flags select three warmup iterations, five measurement iterations, and two forks. Increase them when results are noisy or the benchmark is important.
Running from Code
The Runner API is useful from an IDE:
Options options = new OptionsBuilder()
.include(FoldingBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(options).run();Reading Results
JMH reports a score, an error estimate, and a unit. In average-time mode, a score of 12.4 ns/op means one operation took 12.4 nanoseconds on average. The ± value describes statistical uncertainty, not a performance guarantee. Compare benchmarks only when their mode, input, JVM, hardware, and configuration match.
Multiple Threads and Profilers
Use @Threads(4) to test four concurrent benchmark threads. Confirm that the shared state and operation are thread-safe. More threads can expose contention rather than single-thread performance.
The GC profiler helps explain allocation-related results:
java -jar target/benchmarks.jar FoldingBenchmark -prof gcInspect allocation and garbage-collection metrics alongside the score. A slower benchmark may allocate more objects, trigger more collections, or contend for shared resources.
Exercise
Why should a benchmark input usually be stored in @State instead of written as a literal inside the @Benchmark method?
Show answer
State prevents the JIT from treating the input as a known constant and folding the computation before measurement.