How does Java's autoboxing and unboxing mechanism work at the bytecode level, and what specific performance and correctness pitfalls does it introduce in seemingly innocuous code, such as within a loop?
Short answer
Autoboxing automatically converts a primitive value to its corresponding wrapper object (int to Integer via Integer.valueOf(), which the JVM's small-integer cache -128 to 127 may satisfy from a pre-existing cached instance rather than allocating a new one) when a primitive is…
Advertisement
AModel answer
Autoboxing automatically converts a primitive value to its corresponding wrapper object (int to Integer via Integer.valueOf(), which the JVM's small-integer cache -128 to 127 may satisfy from a pre-existing cached instance rather than allocating a new one) when a primitive is used where an object reference is expected (like adding to a generic collection), and unboxing does the reverse (calling .intValue() automatically) when an object is used where a primitive is expected -- a notorious performance pitfall occurs when this boxing/unboxing happens repeatedly and invisibly inside a tight loop (like accumulating a sum into a boxed Long inside a loop, where each += operation unboxes, adds, and reboxes a brand new Long object every single iteration), and a notorious correctness pitfall occurs when comparing boxed values with == (as covered earlier regarding Integer caching) rather than .equals().
// Hidden performance cost: repeated unboxing/reboxing inside a loop
Long sum = 0L; // boxed type
for (int i = 0; i < 1_000_000; i++) {
sum += i; // each iteration: unbox sum, add, REBOX into a brand new Long object -- expensive!
}
// Better: use the primitive type directly for accumulation
long sum2 = 0L;
for (int i = 0; i < 1_000_000; i++) {
sum2 += i; // no boxing overhead at all
}Real-world example
A performance profiling session on a data-aggregation service reveals an unexpectedly large number of Long object allocations, traced to an accumulator variable being declared as the boxed Long type instead of the primitive long, causing a new Long object to be allocated on literally every single iteration of a hot summation loop, fixed with a one-line type change.
Likely follow-ups
- What is the Integer cache, and why does it only apply to a specific range of small integer values rather than all integers?
- How would you detect excessive autoboxing-related allocation in a profiler's output?
Related topics