Sub topic 16
Change one thing, then measure again
Prerequisites
This chapter assumes you can run Java from the command line and read a stack trace. It also assumes you have seen a Java Flight Recorder (JFR) recording, a GC log, and a JMH benchmark from earlier chapters. Here they are used together as one repeatable workflow.
Why one change at a time
A performance fix is a hypothesis: "this method is slow because of X, and removing X will improve the metric." You can only test a hypothesis if one thing differs between the "before" and "after" runs.
If you change the algorithm, the heap size and the GC at the same time, a faster result tells you nothing about which change helped. One of the three may even have made things worse, hidden by the other two. Changing one thing keeps cause and effect visible.
The loop has five steps:
- Set a goal and a baseline. Write down the metric (for example p99 latency under 200 ms) and measure the current value.
- Profile under a realistic load and find the largest cost.
- Form one hypothesis and make one change.
- Re-measure under the same conditions as the baseline.
- Keep the change if the metric improved beyond the noise. Otherwise revert it, and go back to step 2.
Build a baseline you can trust
A baseline is only useful if you can reproduce it. Fix everything you can control:
- The same JDK version and the same JVM flags.
- The same input data and the same load shape.
- The same machine, ideally without other busy processes.
- A warmup period, so the JIT compiler has finished its work before you measure (see the JIT warmup chapter).
Then run the measurement several times, not once. The spread between runs is your noise level. If three baseline runs give 410, 395 and 450 ms, a "fix" that produces 400 ms has not shown anything. An improvement should be clearly larger than the run-to-run spread.
Record the baseline somewhere durable, such as a text file in the repository next to the commit hash. Without a written number, memory will rewrite it.
A worked example
The Slow program from earlier chapters concatenates strings in a loop. Here it is again.
import java.util.ArrayList;
import java.util.List;
public class Slow {
public static void main(String[] args) {
long start = System.nanoTime();
for (int round = 0; round < 200; round++) {
String s = "";
for (int i = 0; i < 5_000; i++) {
s += i;
}
if (s.length() == 0) {
System.out.println("unreachable");
}
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
}Step 1: baseline. Run the program five times and note each printed time. Also record a profile of one run:
java -XX:StartFlightRecording=duration=60s,filename=app.jfr,settings=profile SlowStep 2: profile. In the recording, the hot methods are string copying and allocation. Each s += i creates a new String and copies every character of the old one. The cost grows with the square of the string length, and the allocation rate is high.
Step 3: one change. Replace the string with a StringBuilder and change nothing else:
public class Fast {
public static void main(String[] args) {
long start = System.nanoTime();
for (int round = 0; round < 200; round++) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5_000; i++) {
sb.append(i);
}
String s = sb.toString();
if (s.length() == 0) {
System.out.println("unreachable");
}
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
}Step 4: re-measure. Run it five times with the same flags and the same machine. Record a second JFR file and compare the allocation and CPU views with the first. The time should drop by a large factor, and the allocation rate should fall. Your own numbers will differ by machine, so compare against your own baseline.
Step 5: decide. The gap between the two sets of runs is far larger than the spread inside each set, so keep the change.
Note that the second recording is as important as the timing. It confirms the mechanism: the hot copying frames should be gone. If the time improved but the profile still shows the old hot method, your explanation was wrong and the improvement came from somewhere else.
Verify with more than one signal
A single number can mislead. Check several signals before you declare success:
| Signal | Tool | What to look for |
|---|---|---|
| Latency or throughput | Load test, application metrics | Goal metric moved beyond noise |
| CPU hot methods | JFR execution samples | Old hot frame gone or reduced |
| Allocation rate | JFR allocation events, GC log | Fewer bytes allocated per request |
| GC pauses | `-Xlog:gc*` | Fewer or shorter pauses |
| Memory footprint | `jstat -gcutil`, heap dump | No growth in old generation |
Compare the GC log before and after:
java -Xlog:gc*:file=gc.log:time,uptime,level,tags -jar app.jarA change that cuts CPU time but doubles the allocation rate may look good in a short test and hurt in production, where GC work competes with request threads.
Use JMH to confirm a local change
When the hot spot is one small method, a JMH benchmark isolates it from the rest of the system. This is the right tool to confirm that a code change helps, because it handles warmup, forking and dead-code elimination for you.
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
public class ConcatBenchmark {
private String a = "hello";
private String b = "world";
@Benchmark
public String plus() {
return a + b;
}
@Benchmark
public String builder() {
return new StringBuilder().append(a).append(b).toString();
}
}JMH prints a score with an error margin for each method. If the intervals overlap, you cannot claim a difference. In this particular case, the two methods are likely close, because the compiler turns a single a + b expression into efficient code. This is a good reminder that the loop in Slow was expensive because of repetition, not because + is always slow.
Common errors
- Changing several things at once. You lose the ability to attribute the result. If you must combine changes, test each one alone first.
- Optimizing without a profile. Intuition about hot spots is often wrong. Profile first, as the earlier chapters showed.
- Measuring on a different setup. Comparing a laptop baseline to a server result mixes the hardware difference into your result.
- Ignoring noise. Treat any difference smaller than the run-to-run spread as no difference.
- Skipping warmup. Early iterations run in the interpreter and measure compilation, not steady-state code.
- Stopping at a faster number. Confirm in the profile that the mechanism you targeted actually changed.
- Fixing a small cost. A method that takes 2% of CPU can at best give a 2% gain. Work on the largest cost first, then re-profile, because the next-largest cost often changes after each fix.
- Not reverting a failed change. Leftover "maybe helpful" edits add complexity and confuse later measurements.
Knowing when to stop
Return to the goal you wrote in step 1. When the metric meets it under realistic load, stop. Further tuning costs time, adds code complexity, and risks new bugs for gains nobody asked for.
If the goal is not met and the profile is flat, meaning no single method dominates, the remaining options are usually structural: a different algorithm, caching, batching, fewer remote calls, or more hardware. These are larger changes, and the same rule applies to them: make one, measure it, and decide.
Exercises
Exercise
You change a hash map's initial capacity, switch the garbage collector, and rewrite an inner loop in one commit. Latency improves by 12%. The run-to-run spread of your baseline is 3%. What is wrong with concluding that all three changes helped, and what should you do?
Show answer
The improvement is real (12% is well above the 3% noise), but it cannot be attributed to any single change. One change may have caused all of the gain while another did nothing or made things worse. Revert to the baseline and apply each change separately, measuring after each one. Keep only the changes that improve the metric beyond the noise.
Exercise
After replacing string concatenation with a StringBuilder, your benchmark time drops by 40%, but the new JFR recording still shows the same method as the top CPU hot spot. What does this suggest, and what is your next step?
Show answer
It suggests that your hypothesis about the mechanism was wrong, and the 40% gain came from something else, such as a different input, a different warmup state, or a change in machine load. Verify that the baseline and the new run used the same conditions, repeat both measurements several times, and then investigate the method that is still hot, since it is still the largest cost.