0Pricing
Java Academy · Lesson

Avoiding Dead-Code Elimination

Blackhole and state.

Avoiding Dead-Code Elimination

The single biggest microbenchmark trap is dead-code elimination (DCE): if the JIT proves a result is never used, it deletes the computation. Your benchmark then measures nothing. JMH gives you two tools to prevent this — returning values and the Blackhole.

The DCE Trap

This loop computes a square root a million times but never uses the result. A smart compiler can delete the entire loop.

public class Main {
    public static void main(String[] args) {
        long t = System.nanoTime();
        for (int i = 0; i < 1_000_000; i++) {
            double ignored = Math.sqrt(i); // result thrown away
        }
        System.out.println("ns: " + (System.nanoTime() - t));
    }
}

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