Lesson · Performance, Profiling & Benchmarking
Performance, profiling and benchmarking
13 min readPerformance, Profiling & Benchmarking
Performance work is measurement with a hypothesis, not optimism with a stopwatch. This lesson covers the metrics worth quoting, why naive benchmarks lie, what JMH and a profiler each buy you, and the loop that ends when the budget is met.
Name the metric and the workload first
"The checkout endpoint is slow" cannot be verified, reproduced or closed. Slow compared to what, on which workload, at which percentile? The first move in any performance task is to replace the sentence with a metric and a workload, because otherwise every change afterwards is as defensible as the last.
A usable statement reads: p99 latency of POST /checkout under the recorded 200 requests per second workload. Now there is a number to move, a scenario to replay, and a definition of done. Choose the metric family deliberately, because chasing all of them at once chases none.
- Latency at a percentile: the response time of a request, quoted at p50, p99 or p999. The default choice for anything user-facing.
- Throughput: work completed per second. The metric when the answer is a batch job or a queue drain, not a person.
- Allocation rate: bytes allocated per second, which is often the real cause behind pause frequency and CPU spent in the collector.
- Startup time: time to first useful response. Dominates serverless, CLI tools and anything that scales to zero.
A performance claim without a workload is an opinion with a number attached. Write the metric and the workload down before touching an editor.
Averages hide the pain
An average is the one number that conceals the thing you are paid to fix. If one request in a hundred takes two seconds, the mean barely moves while the user who got that request experiences an outage, and their retry arrives as extra load.
Percentiles say what fraction of requests were at or below a value: p50 is the median request, p99 is the slowest one in a hundred, p999 the slowest in a thousand. Tail latency is the name for p99 and beyond, and it is the region that reacts to garbage collection pauses, queueing and one slow dependency.
| Metric | What it answers | Where it misleads |
|---|---|---|
| p50 | what a typical request costs | looks healthy while the tail burns |
| p99 | what the unluckiest 1 in 100 sees | needs enough samples to be stable |
| p999 | the worst 1 in 1000, often a pause or a lock | still not the maximum; one request can be worse |
| average | very little that is useful | dominated by the tail while hiding it |
- Percentiles need volume. A p999 from two hundred requests is noise; either collect more samples or quote a percentile the sample size can support.
- Coordinated omission explains a whole class of fake results: a closed-loop benchmark that waits for each request before sending the next stops timing during a stall, so the stall never appears in the numbers. Open-loop or arrival-time-aware measurement is the fix.
- Retries amplify tails. A slow request that times out and is retried spends more capacity and makes the next tail worse, which is why p99 is a capacity question, not a comfort question.
Quote the percentile you were asked to move. "p99 went from 480 ms to 210 ms" is a sentence; "the average improved" is a hope.
Why the naive benchmark lies
The most common Java benchmark is a nanoTime pair around a loop, printed to standard output. It usually reports a number that is too good, and four separate mechanisms are responsible.
- Dead code elimination. If the loop computes a value that nobody reads, the JIT removes the computation and the timer measures an empty loop. Sub-millisecond parse times come from exactly this.
- Constant folding. If every input is a literal, the compiler can compute the answer before the loop starts. Feed the loop from a state field or an array, not from constants.
- Cold code. A single run times interpretation, class loading and the first inlining pass rather than the optimised method. The tier mechanics belong to jit, which also owns the rule that a benchmark without warm-up measures the wrong thing; the takeaway here is that warm-up is part of the experiment.
- Observation overhead. Logging inside the timed region, or printing every iteration, adds I/O to the very thing being measured. Log after the timer stops.
If a number is too good to be true, the JIT probably deleted the work. Check that a result is consumed and an input is dynamic before believing the figure.
JMH: the harness that makes micro numbers defensible
JMH is a separate harness, not a library you sprinkle on production code. It forks one or more fresh JVMs per benchmark, runs explicit warm-up iterations, then measurement iterations, and reports the result with an error estimate so you can see whether two configurations actually differ or are the same number twice.
It also removes the traps above by construction: benchmark results must be consumed, normally through a Blackhole, and the JVM is one the harness controls rather than your IDE's warm process. The modes map onto questions: AverageTime and Throughput for steady state, SampleTime when you want a latency distribution instead of a single figure, SingleShotTime for cold start.
- A fork per benchmark keeps one experiment out of the next, at the cost of JVM start-up time per fork. That is the price of isolation, and it is worth paying.
- Warm-up and measurement iterations are part of the result, not boilerplate around it. Report them with the number.
- JMH numbers are the only defensible micro numbers, and they are still micro numbers. Production behaviour is measured in production.
One benchmark answers one question. A benchmark that tries to answer two will be wrong about at least one of them.
Benchmark replay · the number that lied
naive timing
not measured
JMH average
not measured
budget
2.0 ms p99
after fix
pending
prod p99
not checked
flame graph sample
width = share of samples, depth = call stack
no samples yet: the naive loop was never profiled, and a stopwatch has no stacks
It starts with a sentence: p99 of the parse step must be under 2 ms at 200 orders per second. A hypothesis names the metric and the workload before anything is measured, so the work has a definition of done.
Profilers, flame graphs and the right lens
When the question is where the time goes, stop guessing and sample. A sampling profiler records the stacks of running threads at intervals, and the sample counts point at code. An instrumenting profiler records every method entry and exit: exact call counts, significant overhead, and a distorted picture of the hot path.
The practical choices on the JVM are async-profiler and JFR. JFR's capture and inspection commands already belong to jvm-tooling; this lesson owns profilers as a category and how to read their output. Both can produce a flame graph, and the reading rules are what matter.
In a flame graph, width is the share of samples in which a frame was on the stack, so the widest frame on screen owns the most time. Depth is how the code was reached: a tall, thin tower is a caller chain, not a priority. Read the widest frame first, then follow its callers downward to learn how execution gets there.
Two other lenses answer different questions. Allocation profiling shows where objects are born, which is what explains GC pressure and pause frequency; the pause logs and heap dumps that confirm it belong to gc-debugging. Lock profiling shows where threads wait on monitors and on what, which is the tool for a CPU graph that looks idle while latency climbs.
Width is time, depth is context. Optimise the widest frame, and check the callers before believing a thin tower is the problem.
Performance anatomy · read the picture, then the loop
width is time, depth is context
flame graph anatomy
Width is the share of samples in which the frame was on the stack, so the widest amber bar is the target. Depth only says how execution got there: a tall, thin tower is a caller chain, not a priority.
the percentile curve
Heights and labels here are illustrative; the shape is the point. The gap between p50 and p999 is the part users feel, and an average would sit near the second bar claiming the service is fine.
the measurement loop
One change per pass, same workload every pass, and a written stop rule: the loop ends when the metric meets its budget, not when the graph looks interesting.
The classic traps that survive the profiler
These failures show up in real profiles, usually because the optimisation was aimed by intuition rather than by samples.
- Optimising the five percent. A frame holding 5 percent of samples can be halved for a 2.5 percent gain. Sort by width and start at the top.
- String concatenation in a hot loop.
total += nameinside a loop allocates a new String per iteration; a StringBuilder or one formatted call is the cheap fix, and the audit-log example in the visual is exactly this bug. - Boxing in numeric loops. A
List<Integer>or a stream of boxed values allocates a wrapper per element. A primitive array or a primitive stream avoids the allocation and the cache misses that follow it. - Megamorphic call sites. One interface call that sees many receiver types can stop the JIT from inlining, because it cannot commit to a target. The fix is usually a shape change, such as splitting the call or hoisting a check, not a flag.
- A hash map where an array would do. For dense integer keys, an array lookup skips hashing, equals and pointer chasing. This is the classic map-to-array win in tight numeric loops.
- Measuring a debug build or an IDE run. Debug flags, an attached agent and a run configuration all change what the JIT does. Benchmark the packaged artifact with the flags you actually ship.
The profiler does not care what you expected. Every item above is a hypothesis until the samples agree with it.
The loop, and when to stop
The work has one shape: hypothesis, measure, profile, fix one thing, measure again. Each pass either moves the metric or falsifies the hypothesis, and both outcomes are progress as long as the measurement is honest.
- Write the hypothesis and the metric together: "the audit log concatenation dominates p99 on the checkout path".
- Measure the metric on the target workload before changing anything, with enough samples for the percentile to be stable.
- Profile to find where the time actually goes, choosing one lens per question: CPU, allocation, or locks.
- Change one thing, chosen because it is the widest frame, not because it is the most interesting code.
- Re-measure the same metric on the same workload. If it did not move, revert the change instead of rationalising it.
- Stop when the metric meets its budget, and record the before and after so the next person starts from a baseline.
One change at a time is not slowness, it is attribution. Two changes and one moved number tell you nothing about which one worked.
What to keep
Measure on the workload you actually run, quote the percentile you were asked to move, trust forked and warmed harnesses over stopwatches, profile before optimising, and change one thing per pass. The tooling is replaceable; the loop is not.
The only performance number worth quoting is the one measured on the workload you actually run.
The optimisation that moved the wrong number
A microbenchmark says a method got four times faster, the change ships, and the p99 in production does not move at all. Either the method was not on the hot path, or the benchmark was not measuring what the workload does: different input sizes, no warm-up, or a JIT that deleted the work. Re-measure the metric that motivated the work, on the workload that reported it. If that number did not move, the optimisation is a story, not a win.
Interview angles
Why does a naive microbenchmark usually report nonsense?+
Dead code elimination deletes work whose result nobody reads, constant folding precomputes literal inputs, and a single cold run times interpretation and class loading rather than optimised code. JMH removes all three: fresh forked JVMs, explicit warm-up, and a Blackhole that consumes the result.
The sub-millisecond result is the tell. If a benchmark claims that parsing a document takes less time than reading it from memory, the work was almost certainly deleted before the timer looked at it.
How do you read a flame graph?+
Width is the share of samples and depth is the call stack. The widest frame on screen is the biggest single consumer, so that is the target; a tall, thin tower is context, not priority. Read down from the widest frame to see which callers lead into it.
Why report p99 rather than an average?+
Because the average hides the tail, and the tail is where users are hurt: a handful of two-second requests barely move the mean while they break the experience for the people who receive them. Retries make it worse by adding load, which is why p99 is also a capacity number.
Common misconception: That a good median means the service is healthy. A service can sit at 40 ms p50 and still time out for one request in a hundred, and the report that matters to the user is the one they received.
Someone says the service is slow. What is your sequence?+
Name the metric and the workload, measure a baseline, profile to find the widest frame, change one thing, and re-measure the same metric on the same workload. Stop when the metric meets its budget, and close with the number that opened the investigation.
Follow-up: And if the profile shows the JVM rather than your code? Then the metric moves to allocation rate and pause behaviour, and the evidence comes from GC logs and heap analysis rather than from the CPU flame graph.