JIT compilationmedium3-5 years

A code review comment says "this method allocates a small, short-lived object every call in a hot loop — that's going to hurt GC." Is that always true in Java, and what would you actually check before rewriting the code to avoid the allocation?

Not always — it depends on whether the object ever actually leaves the method (stored in a field, returned, passed somewhere the compiler can't see), and the only reliable way to know is to measure, not to read the code and guess. C2, the JVM's optimising compiler, can prove that some short-lived objects never escape their method and eliminate the allocation entirely, replacing the object's fields with plain local variables — a technique called scalar replacement. The lesson measures this directly on a small Money record allocated on every loop iteration: with escape analysis on, only half the expected bytes were actually allocated per call, because one of the two objects created each iteration was proven not to escape and never touched the heap at all. Before rewriting a hot loop to avoid an allocation 'for the GC's sake', the right first step is measuring actual allocation per call (JFR's allocation profiling) rather than assuming every new in a loop is a real cost.

The lesson behind it →
More on JIT compilation