Sub topic 15
Writing reliable microbenchmarks with JMH
This chapter assumes you know basic Java, can run a build from the command line, and have read the earlier chapter on JIT compilation and warmup. A microbenchmark measures one small piece of code in isolation. Hand-written timing loops with System.nanoTime() usually give wrong answers on the JVM. The Java Microbenchmark Harness (JMH) is the OpenJDK tool that avoids the common traps.
Why naive timing fails
The JIT compiler optimizes code as it runs. Three effects distort a hand-written loop:
- Warmup. The first iterations run in the interpreter or in lightly optimized code, so they are slower than steady state.
- Dead-code elimination. If you never use a result, the JIT may remove the computation, and you end up timing an empty loop.
- Profile pollution. A single JVM that runs many benchmarks shares type and branch profiles between them, so one benchmark can change another's speed.
JMH handles each of these with warmup iterations, forked JVMs, and a mechanism to consume results.
A benchmark that compares two approaches
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
public class ConcatBenchmark {
private String a = "hello";
private String b = "world";
@Benchmark
public String plus() {
return a + b;
}
@Benchmark
public String builder() {
return new StringBuilder().append(a).append(b).toString();
}
}Each annotation does one job:
| Annotation | Purpose |
|---|---|
| `@State(Scope.Thread)` | Gives each thread its own instance holding the inputs. |
| `@BenchmarkMode` | Chooses what is measured, such as average time per call. |
| `@Warmup` | Runs iterations whose results are discarded, so the JIT can stabilize. |
| `@Measurement` | Runs the iterations that count. |
| `@Fork(2)` | Repeats the whole run in two fresh JVMs. |
Avoiding dead-code elimination and constant folding
Both methods return their result. JMH passes returned values to a black hole, so the JIT cannot prove the work is unused. If a benchmark computes several values, call Blackhole.consume(value) on each one.
The strings a and b are instance fields, not final constants. If they were constants, the compiler could fold a + b into one literal at compile time, and you would measure nothing.
Running and reading results
Build with the JMH Maven archetype or Gradle plugin, which produce a benchmarks.jar. Then run it:
java -jar target/benchmarks.jar ConcatBenchmarkJMH reports a score with an error, for example 12.3 ± 0.4 ns/op. If the error ranges of two benchmarks overlap, you cannot claim one is faster. Differences also vary between forks, so compare results across forks and not just within one.
Common mistakes
- Running benchmarks from an IDE with other programs busy on the machine.
- Benchmarking with tiny, unrealistic inputs that hide real costs like cache misses.
- Trusting a result without asking whether the code path matches production.
- Using too few forks, which hides run-to-run variation.
Exercise
Why does JMH use @Fork, and what goes wrong if you run every benchmark in one JVM?
Show answer
Each fork starts a fresh JVM, so a benchmark does not inherit JIT profiles, compiled code, or heap state left by earlier benchmarks. In a shared JVM, earlier benchmarks can bias type and branch profiles and change the speed of later ones. Multiple forks also show run-to-run variation.