Lesson 13 / 38
Profiling & Benchmarking
Measure real Java performance with JDK Flight Recorder and Mission Control, and write trustworthy micro-benchmarks with JMH instead of nanoTime loops.
Tools
JDK Flight Recorder (-XX:StartFlightRecording) plus JDK Mission Control give low-overhead production profiling. For micro-benchmarks use JMH — hand-rolled System.nanoTime() loops are wrecked by JIT warm-up, dead-code elimination, and loop hoisting.
A JMH benchmark
JMH warms up the JIT, runs many iterations, and forks a fresh JVM per benchmark so results aren't skewed by earlier runs in the same process.
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public int sumLoop() {
int total = 0;
for (int x : data) total += x;
return total;
}