Video in progress
When is it worth reducing a high allocation rate, and how do you do it without hurting code quality?
It is worth it when the profile shows the GC taking a noticeable share of the CPU or latency budget. I find the 3-5 biggest allocation sources with JFR or async-profiler and fix only those; I don't introduce a "don't create objects" rule across the whole codebase.
📖 Answer
Allocation itself is cheap (TLAB). The cost is indirect: frequent young GCs, premature promotion, polluting the CPU cache. If GC time is 2-3% of total CPU and the latency SLA is being met, I do nothing.
When I act:
- the GC takes 10%+ of CPU, or young GC pauses affect p99;
- the number of nodes is growing because of memory/CPU, and that is money.
The process:
- I take a flame graph with
async-profiler -e allocor a JFR allocation profile. - Usually 80% of allocation comes from 3-5 places. I look at those.
Typical, safe fixes:
// before: a new formatter and mapper on every call
var mapper = new ObjectMapper();
// after: one thread-safe instance
private static final ObjectMapper MAPPER = new ObjectMapper();
- parameterized logging for debug logs:
log.debug("user {}", id), notString.format; - primitive streams and collections (
LongStream, and if needed fastutil/Eclipse Collections) when there is a lot of boxing; - stream the response instead of collecting it into a
byte[]; - a DTO projection in Hibernate, instead of the entity + persistence context;
- create
ArrayList/StringBuilderwith the right size.
What I avoid: object pools we write ourselves. With a modern GC they are often slower (objects land in Old, card marking goes up) and error-prone: an object that isn't returned, one object used by two threads. A pool only for things that are really expensive: connections, big direct buffers.
After each fix I re-measure the allocation rate and p99. If the change doesn't show up in the measurement, I put the code back to the version that is easier to read.
Sign up to mark studied questions and save your progress.