Scrivio Interview library
InternalsIntermediate6 min read · updated 12 November 2026

Consider:

Java
record Point(int x, int y) {}
long sum(int n) {
long s = 0;
for (int i = 0; i < n; i++) {
Point p = new Point(i, i);
s += p.x() + p.y();
}
return s;
}

Will this allocate n Point objects in steady state? How would you check?

In steady state, usually no. Once C2 compiles sum and inlines the Point constructor and the accessors, p never leaves the loop body, so escape analysis lets C2 scalar replace it and no Point objects are allocated; during warmup, in the interpreter and C1, all n objects are allocated normally. We check with JMH and its gc profiler, where gc.alloc.rate.norm close to 0 bytes per operation shows the allocation was removed, and compare with a run using -XX:-DoEscapeAnalysis, which shows about 24 bytes per Point.

Why this question is asked

This small loop is a good test of how well we understand the JIT. Reading the source, it obviously creates n objects. Running it, a profiler may show almost no allocation. Both are true at different moments of the program's life, and knowing when each one holds is what interviewers are after. The question also checks that we know how to measure allocation properly instead of guessing. In this answer, we will recap escape analysis, follow the code through the compilation tiers, measure it with JMH, see which small changes break the optimisation, and confirm the effect by switching it off.

1A Quick Recap of Escape Analysis

HotSpot's C2 compiler, the optimising JIT that compiles the hottest code, runs escape analysis on each method after inlining. It asks, for every new object, whether anything outside the compiled code can see it: a field, a collection, a return value, another thread, or a call that was not inlined. If not, the object does not escape, and C2 can scalar replace it: it drops the object and keeps its fields as plain local values in registers.

Inlining comes first because without it, the calls new Point(i, i), p.x() and p.y() would be calls to other methods, and passing p to them would count as escaping. Record constructors and accessors are tiny, so C2 inlines them easily.

2Following the Loop Through the Tiers

When sum is first called, it runs in the interpreter, which executes new Point(i, i) literally: it allocates a 24-byte object on the heap each time (12-byte header plus two ints, padded to 24). After enough calls, C1 compiles it, and C1 still allocates. Only when C2 compiles the method, or compiles the hot loop through on-stack replacement while it is running, does escape analysis apply.

Java
record Point(int x, int y) {}
long sum(int n) {
long s = 0;
for (int i = 0; i < n; i++) {
Point p = new Point(i, i); // interpreter and C1: a real 24-byte allocation
s += p.x() + p.y(); // C2: inlined to i + i
}
return s;
}
// What C2 effectively runs after inlining and scalar replacement:
long sum(int n) {
long s = 0;
for (int i = 0; i < n; i++) {
int px = i, py = i; // the Point's fields as local values
s += px + py; // no object, no allocation
}
return s;
}
Step throughWhat happens to new Point(i, i) over time
  1. InterpreterAllocates every Point on the heap
  2. C1 compiled codeStill allocates; no escape analysis
  3. C2 compiles sum or the loop (OSR)Inlines the constructor and accessors
  4. Does p escape?Field, collection, non-inlined call
    YesKeep the heap allocationNoScalar replace p
  5. Steady stateZero bytes allocated per iteration

5 steps in order. Play them, or step through them one at a time.

Notice that the program's result is identical in both versions; sum(4) is 12 either way. The difference is only in how much garbage is produced. During warmup we see the allocations, and in steady state they disappear.

3Measuring It With JMH

Measuring allocation in a quick main method is unreliable, because we do not know which tier is running. JMH, the OpenJDK microbenchmark harness, warms the code up first and its gc profiler reports allocation normalised per operation.

Java
@State(Scope.Thread)
public class PointBench {
@Param("1000") int n;
@Benchmark
public long sum() { return Sums.sum(n); }
}
// java -jar benchmarks.jar PointBench -prof gc
// Benchmark (n) Mode Cnt Score Units
// PointBench.sum 1000 avgt 5 310.2 ns/op
// PointBench.sum:gc.alloc.rate.norm 1000 avgt 5 ~0.001 B/op <- allocation removed
// java -jar benchmarks.jar PointBench -prof gc -jvmArgsAppend -XX:-DoEscapeAnalysis
// PointBench.sum:gc.alloc.rate.norm 1000 avgt 5 24000.0 B/op <- 1000 Points x 24 bytes

The second run is the control. With escape analysis disabled, the benchmark allocates exactly what the source code says: 1,000 Points of 24 bytes each per call. The first run shows a value close to zero, which means C2 removed the allocation. Timings vary by machine; the allocation numbers are what we are checking.

4Changes That Break the Optimisation

Scalar replacement is fragile because it depends on proof. Any change that lets p be seen outside the compiled code turns the allocation back on.

Java
List<Point> seen = new ArrayList<>();
Point last;
for (int i = 0; i < n; i++) {
Point p = new Point(i, i);
last = p; // stored in a field: escapes
seen.add(p); // stored in a collection: escapes
audit(p); // escapes if audit() is not inlined (too large, megamorphic)
Point q = (i % 2 == 0) ? p : new Point(0, 0); // merge across control flow: may defeat C2
s += q.x();
}
Will p be scalar replaced?
Change to the loopEffect on allocation
As writtenRemoved in C2 code
p stored in a field or collectionAllocated: p escapes
p passed to a small method that is inlinedUsually removed
p passed to a large or megamorphic methodAllocated: the call is not inlined
p merged with another new object in a branchDepends on JDK version
Running in interpreter or C1Allocated

The last case is subtle. When a variable may hold one of two different new objects depending on a branch, C2 historically could not scalar replace either of them. Recent JDKs have improved how C2 handles such merges, so whether this shape allocates depends on the version, which is one more reason to measure.

5Follow-up questions

Why might adding a logging call that takes p break the optimisation?

Because a call like log.debug("point {}", p) passes p to a logging framework method that C2 usually does not inline completely: the logger is an interface, its implementation is large, and when logging is enabled the argument is stored in a logging event or formatted through toString(). From C2's point of view, p now escapes, so it must be a real object, even when debug logging is switched off at runtime, because C2 cannot always prove the branch inside the logger is never taken. C2 also has no partial escape analysis, the technique Graal uses to allocate only on the path that escapes. To keep the loop allocation-free, we can log the primitive values, p.x() and p.y(), or log outside the hot loop.

Would sum be optimised if it were called only once with a huge n?

Yes, usually. HotSpot detects the hot loop while it is running and compiles it with on-stack replacement, switching to the C2 version in the middle of the loop. Escape analysis applies to that compiled loop as well, so most iterations allocate nothing.

Does it matter that Point is a record?

Only indirectly. Records have small, final accessors and constructors that inline easily, and their fields are final, which makes analysis simpler. A normal class with the same small methods would be optimised the same way.

6Conclusion

In this answer, we saw that the loop allocates n Point objects while sum runs in the interpreter and C1, but once C2 compiles it and inlines the constructor and accessors, p does not escape and scalar replacement removes the allocation. Storing p in a field or collection, passing it to a method that is not inlined, or some merges across control flow make it allocate again. JMH with -prof gc shows gc.alloc.rate.norm near 0 bytes per operation, and -XX:-DoEscapeAnalysis gives the control run with 24 bytes per Point.

What to say in the interviewAbout 90 seconds aloud

Open with

In steady state it should allocate nothing. Once C2 compiles sum, it inlines the record's constructor and the x and y accessors, and then p is only used inside the loop body.

Then, if they want more

Escape analysis proves it never leaves the compiled code, so C2 scalar replaces it: the two fields become local ints and there is no heap object at all. But that only holds for C2 code. While sum runs in the interpreter and in C1 during warmup, every new Point really allocates 24 bytes, a 12-byte header plus two ints, padded.

If sum were called just once with a huge n, on-stack replacement would compile the loop mid-run and the same optimisation applies. To check, I would write a JMH benchmark and run it with the gc profiler. If gc.alloc.rate.norm is close to 0 bytes per operation, the allocation is gone.

Then I would run it again with DoEscapeAnalysis turned off, which should show about 24,000 bytes per operation for n of 1,000, matching the source.

I would also mention what breaks it: storing p in a field or collection, passing it to a method C2 does not inline because it is large or megamorphic, such as a logging call, or merging different new objects across branches, which depends on the JDK version.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Consider: record Point(int x, int y) {} long sum(int n) { long s = 0; for (int i = 0; i...": https://scrivio-interview-library.netlify.app/java/memory-layout/1ea920441f/