Video in progress

This JMH benchmark shows the new parser is 50 times faster. Do you trust the result?

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class ParserBench {
    @Benchmark
    public void newParser() {
        FastParser.parse("2024-05-17T10:15:30Z");
    }

    @Benchmark
    public void oldParser() {
        OldParser.parse("2024-05-17T10:15:30Z");
    }
}

No. Because the result isn't used, the JIT may remove the computation as dead code, and because the input is a constant, constant folding applies too. You need to return the result or pass it to a Blackhole, and read the input from a @State.

📖 Answer

There are two classic traps.

Dead code elimination. newParser() returns nothing and writes the result nowhere. If FastParser.parse has no side effects and C2 inlines it fully, the whole call is removed, and you are measuring an empty method. The old parser is more complex, so it may not have been inlined and did real work. That is where the difference comes from.

Constant folding. The input is a literal. The JIT may compute some of the work at compile time.

The right version:

@State(Scope.Thread)
@Warmup(iterations = 5) @Measurement(iterations = 10) @Fork(3)
public class ParserBench {
    String input;
    @Setup public void setup() { input = "2024-05-17T10:15:30Z"; }

    @Benchmark public Instant newParser() { return FastParser.parse(input); }
    @Benchmark public Instant oldParser() { return OldParser.parse(input); }
}

On top of that, what I check:

  • -prof gc, so the allocation difference shows too;
  • instead of a single input, a real data set (different lengths, malformed formats), otherwise branch prediction gives an overly optimistic result;
  • @Fork of at least 2-3, because JIT decisions differ between forks;
  • read the results with their error margin.

One more question: does this micro-benchmark matter at all? If the parser takes 0.5% of request time, even a 50x speedup is invisible to the user. That is why I always start with a profile, not with a benchmark.