Sub topic 12
The Cost of Boxing and How to Avoid It
This chapter assumes you know Java primitive types, wrapper classes, generics, loops, and basic streams. You should also understand that int stores a value directly, while Integer stores a reference to an object.
Boxing is the conversion from a primitive to its wrapper object. Unboxing is the reverse conversion. Java can insert both conversions automatically:
Integer boxed = 10; // boxing: Integer.valueOf(10)
int value = boxed; // unboxing: boxed.intValue()These conversions make APIs easier to use, but they can add CPU work, memory use, and garbage-collection pressure.
Where boxing costs appear
Generics cannot use primitive type arguments. For example, List<int> is illegal, so a list of numbers must use List<Integer>. Each element is therefore represented by an Integer reference.
import java.util.ArrayList;
import java.util.List;
public class BoxingInCollections {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 1_000_000; i++) {
numbers.add(i); // boxes i into an Integer
}
int total = 0;
for (Integer number : numbers) {
total += number; // unboxes number
}
System.out.println(total);
}
}The add(i) call boxes each int. The enhanced for loop then unboxes each Integer when adding it to the primitive variable. Some values may come from a wrapper cache, but you should not assume that boxing is free or that every value is cached.
Boxing also appears in APIs that accept objects:
static void accept(Object value) {
System.out.println(value);
}
accept(42); // int is boxed into Integer, then passed as ObjectA single conversion is usually insignificant. A conversion inside a large loop or a frequently called method can become measurable.
Primitive accumulators versus wrapper accumulators
This code uses a Long accumulator:
public class AccumulatorCost {
public static void main(String[] args) {
Long boxedSum = 0L;
for (long i = 0; i < 1_000_000; i++) {
boxedSum += i;
}
long primitiveSum = 0L;
for (long i = 0; i < 1_000_000; i++) {
primitiveSum += i;
}
System.out.println(boxedSum);
System.out.println(primitiveSum);
}
}The statement boxedSum += i is roughly equivalent to:
boxedSum = Long.valueOf(boxedSum.longValue() + i);Each iteration unboxes the old value, performs primitive addition, and boxes the result again. The long accumulator performs only the addition.
| Code choice | Typical representation | Main concern |
|---|---|---|
| `long sum` | Primitive value | Efficient for numeric computation |
| `Long sum` | Wrapper reference | Boxing and possible allocation |
| `List<Long>` | References to wrappers | Required by generic collections |
| `LongStream` | Primitive stream values | Avoids wrapper elements |
Primitive streams
The general Stream<T> API works with objects, so Stream<Long> can box values. Java also provides IntStream, LongStream, and DoubleStream for primitive values.
import java.util.stream.LongStream;
public class PrimitiveStreamExample {
public static void main(String[] args) {
long sum = LongStream.range(0, 1_000_000)
.sum();
System.out.println(sum);
}
}Prefer a primitive stream when the pipeline mainly performs numeric operations. A primitive stream can avoid wrapper objects and provide operations such as sum, average, and summaryStatistics.
The choice still depends on the surrounding code. Converting repeatedly between Stream<Long> and LongStream can make code harder to read and may remove the benefit. Measure important hot paths rather than optimizing every small loop.
Practical decisions
Keep values primitive when:
- The value is always present.
- The code performs arithmetic in a loop.
- The data uses a primitive stream.
- You are working in a performance-sensitive section.
Use wrappers when:
- A collection or generic API requires them.
nullhas a meaningful “missing” state.- An API requires an object.
- You need methods such as
Integer.parseIntorInteger.compare.
Do not replace every wrapper automatically. Object allocation is only one factor. Memory layout, cache behavior, algorithm choice, and I/O often matter more. Use a profiler or benchmark when performance is important.
Exercise
In the expression Long total = 0L; total += 5L;, which conversions occur, and what declaration avoids them during repeated arithmetic?
Show answer
The old Long is unboxed with longValue(), the values are added as primitives, and the result is boxed with Long.valueOf(). Declaring the accumulator as long total = 0L avoids those repeated conversions.