Video in progress
What is OSR (on-stack replacement), and how does it distort micro-benchmark results?
OSR swaps a method stuck inside one long loop for a compiled version in place, without waiting for it to finish. Such code is optimized worse than normally compiled code, so a result measured with a loop inside main doesn't reflect the real situation.
📖 Answer
Normally a method is compiled when it is called a lot. But main is called once and has a loop inside that runs a billion times. The JVM counts the loop's backward jumps and, once past a threshold, compiles a special OSR version for the loop and moves the running frame into it.
Here is a classic bad benchmark:
public static void main(String[] args) {
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 1_000_000_000; i++) {
sum += i % 7;
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
There are many problems: the first part runs in the interpreter, and then the OSR code is of a different quality; if the result isn't used, the JIT may remove the loop entirely (dead code elimination); GC and compilation leak into the measurement.
That is why micro-benchmarks in Java are only written with JMH. It does separate warm-up iterations, runs every benchmark in its own fork, passes the result to a Blackhole and produces statistics.
A good interview answer: "I don't measure by hand with nanoTime, I use JMH and check the result with -prof gc and -prof perfasm". And one more thing: a 20% speedup in a micro-benchmark often doesn't show up in a real service.
Sign up to mark studied questions and save your progress.