The BackendDeeper

Kayavak / The Backend / BE·41 Memory and Performance / Deeper

Deeper · The Backend

Memory and Performance

The questions the chapter doesn't stop for: why this exists, the model to keep in your head, what changes when an assumption does, how sure we are of each claim, and what's still open. Read it after the chapter; back to the chapter.

Why does this exist?

"Premature optimization is the root of all evil" comes from Donald Knuth's 1974 paper Structured Programming with go to Statements, and the full sentence is more useful than the slogan: we should forget about small efficiencies about 97% of the time, but not pass up our opportunities in that critical 3%. Finding the 3% is the subject of this chapter.

Tools for finding it improved slowly. Sampling profilers appeared with Unix (prof, then gprof in 1982), but on the JVM most profilers suffered safepoint bias, only sampling at points the JVM chose, so they blamed the wrong code. Async-profiler and Java Flight Recorder (open-sourced in Java 11, 2018) sample without that bias and cheaply enough for production. Brendan Gregg's flame graphs (2011) made the results readable at a glance.

The mental model

Try it yourself first: write your own model in the Mental Model Explorer, then compare.

Performance work is an experiment: state a goal, measure, form a hypothesis, change one thing, measure again. Memory is what you keep; allocation is what you make; time usually goes where you didn't expect.

Question Answer
What is it? Making a system meet a latency, throughput or memory goal, by evidence
Problem it solves Slow or expensive systems, without breaking correctness or guessing
Parts Goals (percentiles), benchmarks (JMH), profilers (CPU, allocation, locks, wall-clock), heap analysis, object layout
How it works Measure the real system first, find the biggest cost, fix it, re-measure the same way
Assumptions The benchmark represents real use; the change is the only variable
When they change Microbenchmarks without warm-up measure the interpreter; dead-code elimination measures nothing
Where it fails Optimising something that isn't the bottleneck; trading readability for gains nobody needed
Related ideas Caches (Foundations, ch07); JIT (ch40); capacity planning (Observability and SRE)

What if?

What if you halved the time of a function that takes 10% of a request?

Reason it through, then open

The request gets 5% faster, at best. Amdahl's law applies to latency as well as to cores (ch38): the improvement is bounded by the share of time the part actually takes. That's why the first step is a profile of the whole request, which often shows a database call or network wait dwarfing all the code.

What if your JMH benchmark's result is never used?

Reason it through, then open

The JIT may notice the computation has no effect and delete it, so you'd measure an empty loop and report an absurd speed. JMH's Blackhole (or returning the result) keeps the work alive. Benchmarks also need warm-up, several forks and attention to constant folding; JMH exists because naive timing loops get these wrong.

Where the boundary is

Aspect Memory footprint Allocation rate
Means Bytes live at a moment Bytes created per second
Shown by Heap histograms, heap dumps Allocation profilers, JFR
Problem when high Out of memory, large heaps GC work, CPU, cache pollution
Can differ A scan allocating nothing has zero allocation and can still be slow

Derive it

Little's law: how many requests are in a system.

  1. Let requests arrive at an average rate λ per second, and each stay an average W seconds.
  2. Plot, over a long period T, how many requests are inside at each moment. The area under that curve is the total request-seconds spent inside.
  3. Counted per request, the same area is roughly (number of requests) × W = λT × W.
  4. The average number inside, L, is that area divided by T: L = λW.
  5. So a service handling 2,000 requests per second at 50 ms each has about 100 in flight at any moment, which sizes thread pools, connection pools and queues. If latency rises to 500 ms at the same rate, 1,000 are in flight: one reason slow dependencies exhaust pools.

How sure are we?

Claim How it's known Where from
L = λW for any stable system Theorem John Little, 1961; holds regardless of arrival or service distributions
Knuth's "premature optimization" sentence and its 97% context Historical Knuth, 1974
Many JVM profilers had safepoint bias Measured Studies of profiler accuracy (e.g. Mytkowicz et al., 2010)
A 12-byte header (8 with compact headers) Convention HotSpot's layout with compressed class pointers; varies by flags and version

Still open

Profiling accuracy is still studied; profilers can disagree about the same program. How to keep performance from regressing in continuous delivery (benchmarks in CI are noisy) is a practical open problem.

What would change your mind? If two profilers consistently agreed on your hotspot and fixing it didn't help, your benchmark doesn't represent the real workload.

Recall

What does Little's law say?

Average number in a system = arrival rate × average time in the system (L = λW).

What's the full point of Knuth's "premature optimization" remark?

Ignore small efficiencies most of the time, but don't miss the critical few percent; find them by measuring.

Why might a JMH benchmark measure nothing?

The JIT can eliminate work whose result is unused; use a Blackhole or return the result.

What's the difference between footprint and allocation rate?

Footprint is memory kept at a moment; allocation rate is memory created per second.

Reflect

Be honest with yourself; this stays in your browser. Anything you can't tick yet is what to revisit.