This week I wanted to know if a small parser in one of my services should use a regex or plain indexOf. My first try was a for loop with System.nanoTime() around it. I ran it three times and got three different answers. So I set it up again with JMH.
Why the hand-written loop lies
A typical first attempt looks like this:
long start = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
parse("temp=21.5;hum=40");
}
long elapsed = System.nanoTime() - start;
System.out.println(elapsed / 1_000_000 + " ns per call");
Several things go wrong here, and you cannot see any of them from the output.
- JIT warmup. The JVM starts by interpreting the code. After enough calls it compiles the method with C1, and later with C2. The first part of the loop measures the interpreter and the compiler, not your code.
- Dead code elimination. The result of
parseis never used. C2 can see that and remove the call, or most of it. Then you measure an empty loop. - Constant folding. The input is a constant string. If the JIT can compute the result at compile time, it does, and the work disappears again.
- On-stack replacement (OSR). The whole benchmark is one long loop inside
main. The JVM compiles it with OSR, which switches to compiled code in the middle of the loop. OSR code is often not the same as the code you get when the method is called normally from a hot path. - One JVM run. JIT decisions, memory layout and GC timing differ between runs. A single run tells you about that run only.
You can fix some of this by hand (warmup rounds, use the result, run several times), but it is easy to miss one. JMH is made by the OpenJDK people to handle exactly these problems, so I use it instead.
Setting up JMH with Maven
The current version as I write this is JMH 1.36. The quickest start is the archetype:
mvn archetype:generate \
-DinteractiveMode=false \
-DarchetypeGroupId=org.openjdk.jmh \
-DarchetypeArtifactId=jmh-java-benchmark-archetype \
-DarchetypeVersion=1.36 \
-DgroupId=com.example \
-DartifactId=parse-bench \
-Dversion=1.0
cd parse-bench
mvn clean verify
This makes a separate project. The pom has jmh-core, the annotation processor jmh-generator-annprocess, and the shade plugin that builds target/benchmarks.jar. Check that the jmh.version property in the pom says 1.36.
I prefer a separate project, or at least a separate Maven module, for benchmarks. JMH generates code at compile time with the annotation processor. Putting jmh-core into the test scope of your main project and running it from JUnit works sometimes, but it is not what JMH is designed for, and forking does not behave the same way.
If you need to benchmark your own classes, add your main module as a dependency of the benchmark module.
The example
The task: get the value for a key from a line like temp=21.5;hum=40;bat=3.1. One version uses a precompiled regex, the other uses indexOf and substring.
package com.example;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
@State(Scope.Benchmark)
public class ParseBench {
@Param({"temp", "bat"})
String key;
String line;
Pattern pattern;
@Setup
public void setup() {
line = "temp=21.5;hum=40;bat=3.1";
pattern = Pattern.compile("(?:^|;)" + Pattern.quote(key) + "=([^;]*)");
}
@Benchmark
public String regex() {
Matcher m = pattern.matcher(line);
return m.find() ? m.group(1) : null;
}
@Benchmark
public String indexOf() {
String prefix = key + "=";
int start = line.startsWith(prefix) ? 0 : line.indexOf(";" + prefix);
if (start < 0) {
return null;
}
if (start > 0) {
start++;
}
start += prefix.length();
int end = line.indexOf(';', start);
return end < 0 ? line.substring(start) : line.substring(start, end);
}
@Benchmark
public void indexOfTwoKeys(Blackhole bh) {
bh.consume(valueOf(line, "temp"));
bh.consume(valueOf(line, "bat"));
}
static String valueOf(String line, String key) {
int i = line.indexOf(key + "=");
if (i < 0) return null;
int start = i + key.length() + 1;
int end = line.indexOf(';', start);
return end < 0 ? line.substring(start) : line.substring(start, end);
}
}
The indexOf version only accepts the key at the start of the line or after a ;, so temp does not match inside a longer key like airtemp. The simple valueOf helper skips that check. For a benchmark this is fine, but do not copy it into real code without the check.
What each part does:
@Benchmarkmarks a method to measure. JMH calls it in its own loop, written so that the JIT cannot merge iterations or move work out of the loop.@State(Scope.Benchmark)makes a class that holds the input. One instance is shared by all threads.Scope.Threadgives each thread its own instance.@Setupruns before the measurement. By default it runs once per trial (Level.Trial). There is alsoLevel.IterationandLevel.Invocation. AvoidLevel.Invocationunless you know why you need it, because it adds timing overhead to every call.@Paramruns the whole benchmark once per value. Here it runs withtemp(first key) andbat(last key), because the position of the key changes the cost.@Fork(2)runs each benchmark in two fresh JVMs. This is how you see run-to-run variance. Never use@Fork(0)for real results, because then all benchmarks share one JVM and its JIT profile.@Warmupand@Measurementset how many iterations and how long each one is. Warmup results are thrown away.@BenchmarkMode(Mode.AverageTime)with@OutputTimeUnit(TimeUnit.NANOSECONDS)reports nanoseconds per call.Mode.Throughputreports calls per time unit.Mode.SampleTimegives percentiles, which is useful when the cost is not stable.
Return the value or use a Blackhole
Each benchmark returns its result, or passes it to a Blackhole. This is how JMH stops dead code elimination. If a method returns a value, JMH consumes it for you. If you compute more than one value, like indexOfTwoKeys, give each one to bh.consume(...).
The input comes from the state object, not from a constant in the method. Fields in a @State class that are not final are read on every call, so the JIT cannot fold them into a constant. I made line and key normal fields for this reason. If you make them static final, you are back to constant folding.
Running it
mvn clean verify
java -jar target/benchmarks.jar ParseBench
The argument is a regex for the benchmark names. Some options I use often:
# quick check while writing the benchmark (not for real results)
java -jar target/benchmarks.jar ParseBench -f 1 -wi 2 -i 3
# only one parameter value
java -jar target/benchmarks.jar ParseBench -p key=bat
# save results as JSON for later comparison
java -jar target/benchmarks.jar ParseBench -rf json -rff parse.json
# list all options and profilers
java -jar target/benchmarks.jar -h
java -jar target/benchmarks.jar -lprof
Close other heavy programs while it runs. A laptop on battery, or a browser playing video, changes the numbers. JMH also prints a warning at the start that the numbers are not to be trusted blindly. Read it once. It is correct.
Reading the output
At the end JMH prints a table like this (the numbers are left out here on purpose, they depend on your machine):
Benchmark (key) Mode Cnt Score Error Units
ParseBench.indexOf temp avgt 10 ... ± ... ns/op
ParseBench.indexOf bat avgt 10 ... ± ... ns/op
ParseBench.regex temp avgt 10 ... ± ... ns/op
ParseBench.regex bat avgt 10 ... ± ... ns/op
Cntis the number of measurement iterations in total: 5 iterations times 2 forks.Scoreis the mean.Erroris the half-width of the 99.9% confidence interval.
Compare Score ± Error ranges, not only the scores. If the ranges of two benchmarks overlap, you have not shown a difference. Also scroll up and look at the per-iteration and per-fork lines. If one fork is very different from the other, something is not stable (JIT decisions, GC, a noisy machine), and more forks will tell you more than more iterations.
A large error compared to the score is a signal to look closer, not a number to report.
Allocation with -prof gc
For small parsing code, time is often less important than garbage. The GC profiler shows it:
java -jar target/benchmarks.jar ParseBench -prof gc
It adds extra rows per benchmark. The ones I look at:
gc.alloc.rate.normis bytes allocated per operation. This is the most useful one, because it does not depend on how fast the machine is. The regex version allocates aMatchereach call, and both versions allocate the result string. This row shows how much it adds up to.gc.alloc.rateis MB per second. It goes up when the code gets faster, so do not compare it alone.gc.countandgc.timeshow how many collections happened during the measurement.
If one version allocates zero bytes per operation where you expected some, escape analysis removed the allocation. That is real in this benchmark, but it may not happen in the real code, where the object is passed further.
When a microbenchmark is the wrong tool
JMH answers a narrow question: how fast is this piece of code, in isolation, with this input, after warmup. That is useful for library code, parsers, serializers and data structures. It is not useful for most questions about a service.
In a Spring Boot service, a request spends its time in the database, the network, JSON mapping, logging and locks. A parser that is twice as fast in JMH may change nothing in the end-to-end latency. And the JIT may inline and optimise the code differently in the real application, where the call site sees many types and inputs.
So before I write a microbenchmark, I check with a profiler (JFR, or async-profiler) that the code shows up at all in the real service under load. If it does not, I measure the whole service with a load test instead and leave the parser alone. If it does show up, JMH is the right tool to compare the options, and then I check again in the real service after the change.
For my parser, the profile showed it was a small part of the request. I still learned what the regex version allocates, which was the actual reason I cared. I have not yet tried the same benchmark on an ARM board. I expect the ranking could be different there, so I would run it again rather than reuse the result.
The JMH samples in the project repository (JMHSample_* classes) explain each trap with code. They are worth reading in order once.