Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Spot the performance problem and rewrite it:

Java
Long sum = 0L;
for (long i = 0; i < 1_000_000_000L; i++) {
sum += i;
}

Because sum is declared as Long, every sum += i unboxes the current value, adds i, and boxes the result into a new Long through Long.valueOf. Almost all of those values are outside the small Long cache, so the loop allocates close to a billion short-lived objects and keeps the garbage collector busy. Declaring sum as a primitive long removes the boxing and makes the loop many times faster.

Why this question is asked

This snippet is a classic because the bug is a single capital letter. Long and long look almost the same, the code compiles without a warning, and the result is correct, so nothing points at the problem except the time it takes. Interviewers ask it to check that we can see the hidden work that autoboxing adds and that we know why the JIT compiler does not always rescue us. In this answer, we will recap boxing, expand the loop into what the compiler really generates, count the cost, rewrite it, and look at what escape analysis can and cannot do.

1A Quick Recap of Boxing

long is a primitive: a 64-bit number stored directly in the variable. Long is a class that wraps a long in an object on the heap. Java converts between them automatically: assigning a long to a Long boxes it, and using a Long in arithmetic unboxes it. Long objects are immutable, so a Long can never change its value; changing the variable means pointing it at a different Long object.

2What the Loop Really Does

The compiler cannot add to a Long directly. It rewrites sum += i into three steps on every iteration.

Java
Long sum = 0L;
for (long i = 0; i < 1_000_000_000L; i++) {
// sum += i; is compiled as:
long current = sum.longValue(); // 1. unbox
long next = current + i; // 2. add
sum = Long.valueOf(next); // 3. box: a new Long unless next is in -128..127
}
System.out.println(sum); // 499999999500000000
Step throughOne iteration with Long sum
  1. Unboxsum.longValue()
  2. Addcurrent + i
  3. Result in -128..127?
    YesReuse a cached LongNoAllocate a new 24-byte Long
  4. Old Long becomes garbagethe young GC must clean it up

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

Long.valueOf only returns cached objects for -128 to 127. The running sum passes 127 after the 17th iteration and never comes back, so from then on every iteration creates a new Long. That is nearly a billion objects of 24 bytes each on a typical 64-bit JVM, about 24 GB of allocation over the run. Each object is garbage one iteration later, so the collector runs young collections again and again just to throw them away.

3The Fix: Use a Primitive long

Changing one letter removes every allocation. The variable now holds the number itself, and the addition is a single machine instruction.

Java
long sum = 0L;
for (long i = 0; i < 1_000_000_000L; i++) {
sum += i; // one add, no objects
}
System.out.println(sum); // 499999999500000000
// Or with a stream that stays primitive:
long total = LongStream.range(0, 1_000_000_000L).sum(); // 499999999500000000

On typical hardware the primitive loop finishes in well under a second, while the boxed loop takes several seconds or more, depending on the JVM and the collector. The exact ratio varies, so if the number matters we measure it with a benchmark harness such as JMH rather than a stopwatch. Notice also that the result fits easily in a long, whose maximum is about 9.2 x 10^18, so overflow is not a concern here.

4Can the JIT Remove the Boxing for Us?

Sometimes. HotSpot's C2 compiler performs escape analysis: it checks whether an object ever leaves the method or the loop. If the new Long never escapes, the compiler can apply scalar replacement, which keeps the value in a register and never allocates the object. In simple loops like this one, C2 can occasionally remove most of the boxing.

But there is a catch: we cannot rely on it. Escape analysis only runs in compiled code, so the early interpreted iterations still allocate. It gives up when the method is too large, when the object is stored in a field or passed to a method that is not inlined, and when the loop structure is more complex. Different JVMs and versions make different decisions. Code that is fast only because an optimisation happened to fire is fragile, so the right fix is still to write long.

5Follow-up questions

How would you catch this kind of problem in a real service?

An allocation profiler shows it directly. Java Flight Recorder's allocation events or async-profiler in allocation mode will list Long.valueOf as a top allocation site, and a high young-generation GC rate is the visible symptom. Many IDEs and static analysers also warn about boxed types used as loop accumulators.

Is Long ever the right type for a counter?

Only when we need an object, for example to store it in a collection, or to represent absence with null. For a local accumulator there is no reason to use it. If several threads need to update a counter, the right choice is AtomicLong or LongAdder, not Long.

Would Integer sum have the same problem?

Yes, and worse: the sum would also overflow int's maximum of about 2.1 billion. Every iteration would still unbox and box, and Integer.valueOf only caches up to 127 by default.

6Conclusion

In this answer, we saw that declaring the accumulator as Long turns sum += i into unbox, add and box on every iteration, and that Long.valueOf only caches -128 to 127, so the loop allocates nearly a billion short-lived objects and creates heavy GC pressure. Declaring sum as long, or using LongStream, removes all of it. Escape analysis in the JIT can sometimes eliminate such allocations, but it is not guaranteed, so we should fix the type rather than rely on the optimiser.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is that sum is a Long, the wrapper, not the primitive long. Long objects are immutable, so the compiler turns sum += i into three steps: unbox sum with longValue, add i, then box the result with Long.valueOf. valueOf only returns cached instances for minus 128 to 127, and the sum passes that after a handful of iterations, so nearly every one of the billion iterations allocates a new Long, around 24 bytes each.

Then, if they want more

That is roughly 24 GB of short-lived garbage, so the young generation fills constantly and the GC works the whole time. The fix is one letter: declare sum as a primitive long. Then the loop is a plain add in a register, no allocation at all, and it runs many times faster. Alternatively, LongStream.range(0, n).sum() stays primitive end to end.

I would mention that HotSpot's C2 compiler can sometimes remove the allocations through escape analysis and scalar replacement, because the Long never escapes the loop, but that is not guaranteed: it does not apply in the interpreter, it can fail when inlining fails, and it varies by JVM. So I would never rely on it.

To prove the improvement I would use JMH, and in a real service I would look for Long.valueOf in an allocation profile.

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 "Spot the performance problem and rewrite it:": https://scrivio-interview-library.netlify.app/java/types-and-values/054eec87a2/