0Pricing
Java Academy · Lesson

Why JMH

Avoid naive benchmark mistakes.

Why JMH

The Java Microbenchmark Harness (JMH) is the standard tool for measuring the performance of small pieces of Java code. Hand-rolled timing loops almost always produce wrong numbers because the JVM is a sophisticated optimizing runtime.

JMH exists to neutralize those pitfalls.

The Naive Benchmark

A typical first attempt wraps a loop in System.nanoTime(). It looks reasonable but is deeply flawed for microbenchmarks.

public class Main {
    static int compute(int n) { return n * n + 7; }
    public static void main(String[] args) {
        long start = System.nanoTime();
        int sink = 0;
        for (int i = 0; i < 1_000_000; i++) sink = compute(i);
        long elapsed = System.nanoTime() - start;
        System.out.println("ns: " + elapsed + " sink=" + sink);
    }
}

All lessons in this course

  1. Why JMH
  2. Writing a Benchmark
  3. Warmup and Iterations
  4. Avoiding Dead-Code Elimination
← Back to Java Academy