Video in progress
A colleague compared two implementations with this code and wrote the result in the PR. Why can't you trust this measurement?
long t1 = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) parseV1(input);
long t2 = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) parseV2(input);
long t3 = System.nanoTime();
System.out.println("v1=" + (t2 - t1) + " v2=" + (t3 - t2));
There is no warm-up, the JIT may remove the computation entirely because the result isn't used, the first variant is measured in the interpreter and the second after compilation, and GC pauses land by chance. The right way is JMH.
📖 Answer
Several mistakes work together in this code:
- Warm-up.
parseV1is interpreted at first, so half of the measurement is slow code. By the timeparseV2runs, shared code (for example,Stringmethods) is already compiled, so it wins. - Dead code elimination. The result isn't used anywhere. After inlining, C2 can see that all or part of the computation is unneeded and remove it. Then you get the false result "v2 is 1000 times faster".
- OSR. The whole loop is inside one method, so the JIT compiles it with on-stack replacement, which differs from a normal call.
- GC and noise. In a single measurement, a random GC pause or another process spoils the result. There is no distribution and no error margin.
With JMH:
@State(Scope.Benchmark)
@Warmup(iterations = 5) @Measurement(iterations = 10) @Fork(2)
public class ParseBench {
String input = "...";
@Benchmark public Object v1() { return parseV1(input); }
@Benchmark public Object v2() { return parseV2(input); }
}
Returning the result (or Blackhole.consume) stops the JIT from removing it, @Fork runs each variant in a separate JVM, and the result comes with an error margin. If you add -prof gc, you also see how many bytes of allocation each call costs.
Sign up to mark studied questions and save your progress.