Sub topic 12
The cost of boxing and how to avoid it
This chapter assumes you know Java's primitive types, how generics and List/Map work, and the difference between == and equals. It also assumes you have read the earlier chapters on autoboxing, unboxing and the wrapper cache. Here we look at what boxing costs at run time, where that cost shows up in real code, and how to remove it when it matters.
Where the cost comes from
A primitive long is 8 bytes stored directly in a local variable, a field, or an array slot. A Long is an object on the heap. It has an object header (typically 12 to 16 bytes on a 64-bit JVM, depending on settings), then the 8-byte value, then padding. A single Long usually occupies 16 to 24 bytes. A variable of type Long also holds a reference to that object, which is another 4 or 8 bytes.
Boxing therefore has three costs:
- Allocation.
Long.valueOf(x)creates a new object for any value outside the cache range (-128 to 127). Allocation on the JVM is cheap, but it is not free, and each object must later be garbage collected. - Memory. A
long[]of one million elements takes about 8 MB. AList<Long>of one million elements holds one million references plus up to one million separate objects. That is commonly 20 to 28 MB or more. - Indirection. Reading a boxed value means following a reference to another place in memory. A primitive array is contiguous, so the CPU cache works well. A list of boxed values can scatter its objects across the heap, which causes more cache misses.
The JIT compiler can sometimes remove boxing through escape analysis. If a boxed object never leaves a method, the JIT may avoid allocating it. You cannot rely on this. It depends on inlining, on the JVM version, and on how the code is shaped. Treat it as a bonus, not a guarantee.
A loop that boxes on every iteration
The most common source of hidden boxing is a wrapper-typed variable that is updated inside a loop.
import java.util.stream.LongStream;
public class BoxingCost {
public static void main(String[] args) {
Long boxedSum = 0L;
for (long i = 0; i < 1_000_000; i++) {
boxedSum += i; // unbox, add, box a new Long on each iteration
}
long primitiveSum = 0L;
for (long i = 0; i < 1_000_000; i++) {
primitiveSum += i; // no allocation
}
long streamSum = LongStream.range(0, 1_000_000).sum(); // primitive stream, no boxing
System.out.println(boxedSum + " " + primitiveSum + " " + streamSum);
}
}All three computations give the same result. The difference is in what the first loop compiles to. The statement boxedSum += i is not an in-place update, because a Long is immutable. The compiler turns it into roughly this:
boxedSum = Long.valueOf(boxedSum.longValue() + i);Each iteration unboxes the current sum, adds i, and boxes the result into a new Long. For most sums that is a new object per iteration, so about one million short-lived objects in this loop. The second loop does the same arithmetic with no allocation.
The fix is usually one word: declare the accumulator as long, not Long. A wrapper type on a local variable is rarely needed. The main reasons to use one are that you need to store null, or that you are passing the value into a generic API.
Where boxing is unavoidable
Generics work only with reference types. List<int> does not compile, so List<Integer> boxes every element. The same applies to Map<Integer, Integer>, Set<Long>, Optional<Double>, and any generic class you write yourself. Every add, put or get with a primitive crosses the boundary.
import java.util.HashMap;
import java.util.Map;
public class CountWords {
public static void main(String[] args) {
String[] words = {"a", "b", "a", "c", "a", "b"};
Map<String, Integer> counts = new HashMap<>();
for (String w : words) {
counts.merge(w, 1, Integer::sum);
}
System.out.println(counts);
}
}Here the 1 is boxed, Integer::sum unboxes both arguments and boxes the result, and the map stores an Integer. For small counts the cache absorbs most of the cost, since values up to 127 are shared objects. Above that, each increment allocates. For a word-count program that is usually fine. For a counter incremented hundreds of millions of times, it may not be.
The cost is worth removing only when it is measurable. A map with a few hundred entries that is touched a few thousand times will never show up in a profile. A tight numeric loop or a collection with millions of entries might.
Options for avoiding boxing
Use primitive variables and arrays
If the data is a fixed-size sequence of numbers, use int[], long[] or double[]. They are smaller and faster than any list of wrappers. Use java.util.Arrays for sorting, searching and filling.
import java.util.Arrays;
public class PrimitiveArray {
public static void main(String[] args) {
int[] scores = {88, 92, 75, 92, 60};
Arrays.sort(scores);
System.out.println(Arrays.toString(scores));
System.out.println(Arrays.stream(scores).sum());
}
}Use primitive streams
The java.util.stream package has IntStream, LongStream and DoubleStream. They carry primitives through the pipeline without boxing. Compare these two ways to sum squares:
import java.util.List;
import java.util.stream.IntStream;
public class StreamBoxing {
public static void main(String[] args) {
List<Integer> boxed = IntStream.rangeClosed(1, 5).boxed().toList();
// Boxed: each element is an Integer, and reduce unboxes and reboxes
int a = boxed.stream().map(n -> n * n).reduce(0, Integer::sum);
// Primitive: no Integer objects in the pipeline
int b = IntStream.rangeClosed(1, 5).map(n -> n * n).sum();
System.out.println(a + " " + b);
}
}Use mapToInt, mapToLong and mapToDouble to move from an object stream to a primitive stream. Use boxed() to go back only when you need to collect into a List or Map.
Use primitive specializations of functional interfaces
java.util.function contains versions of the common interfaces that avoid boxing: IntPredicate, IntFunction, IntUnaryOperator, IntBinaryOperator, ToIntFunction, LongSupplier, DoubleConsumer, and others. Prefer them over Predicate<Integer> or Function<Integer, Integer> in numeric code. IntBinaryOperator takes and returns int. BinaryOperator<Integer> boxes both arguments and the result.
Use primitive collections from a library
The standard library has no List<int> equivalent. Libraries such as Eclipse Collections, fastutil and HPPC provide them (IntArrayList, Long2IntOpenHashMap and so on). Adopt one only when profiling shows that a large boxed collection is a real problem. It adds a dependency and its own API to learn.
Avoid `Optional` for primitives
Optional<Integer> boxes its value. OptionalInt, OptionalLong and OptionalDouble do not. Primitive streams return these types from methods such as max() and average().
Choosing between options
| Situation | Preferred approach |
|---|---|
| Local counter or accumulator in a loop | Declare it as a primitive |
| Fixed-size numeric data | `int[]`, `long[]`, `double[]` |
| Numeric pipeline over a collection | `mapToInt` and primitive streams |
| Lambdas over numbers | `IntPredicate`, `IntUnaryOperator` and similar |
| Large map or list of numbers in a hot path | Primitive collection library, after measuring |
| Small collections, configuration, non-hot code | `List<Integer>` and `Map<String, Integer>` are fine |
| Value may be absent and absence matters | A wrapper, or `OptionalInt`, not a sentinel hidden in a primitive |
Boxing and the cache are not a performance plan
The cache for -128 to 127 reduces allocation for small values, but it has a cost of its own. Integer.valueOf must check the range and look up the shared object. Do not design code around the cache. The range of the Integer cache can be raised with the -XX:AutoBoxCacheMax option, but relying on that couples your program to a JVM flag. The earlier chapter explained why == on wrappers is a bug regardless of the cache.
Measuring instead of guessing
Micro-benchmarks written by hand are easy to get wrong. The JIT may optimize away code whose result is unused, or compile the code differently after warm-up. The reliable tool is JMH (the Java Microbenchmark Harness), which handles warm-up, forks, and dead-code elimination. In practice, a profiler or a garbage-collection log tells you more: if allocation rate and GC time are high and the allocation profile shows Integer, Long or Double, boxing is a real cause.
Common mistakes
- Using wrappers for local variables by habit. Use primitives unless you need
nullor a generic type. - Calling
boxed()early in a stream. Stay in the primitive stream as long as possible and box at the end. - Replacing a clear design with a premature optimization. A
List<Integer>of 50 items does not need anint[]. - Assuming the JIT removes all boxing. It sometimes does, but code that depends on it can change behavior across JVM versions.
- Mixing boxed and primitive types in a conditional expression. In
cond ? someInteger : 0, theIntegeris unboxed, so anullthrowsNullPointerException. This combines the cost of boxing with the null hazard from the earlier chapter.
Summary
Boxing turns a value into a heap object, which costs allocation, memory and indirection. The cost is largest in loops that update a wrapper variable and in large collections of numbers. Remove it by using primitive variables, arrays, primitive streams, primitive functional interfaces, and OptionalInt and its relatives. Keep ordinary wrapper-based collections wherever the code is not hot, and measure before changing anything more invasive.
Exercise
The method below is slow for large n and creates many short-lived objects. Explain why, then rewrite it so it does not box. Also say how you would sum the squares from 1 to n without any loop. static Long sumOfSquares(int n) { Long total = 0L; for (int i = 1; i <= n; i++) { total += (long) i * i; } return total; }
Show answer
Because Long is immutable, total += x compiles to total = Long.valueOf(total.longValue() + x). Each iteration unboxes the old value and allocates a new Long once the sum leaves the -128..127 cache range, so n iterations create about n objects. The fix is to use a primitive accumulator and return type: static long sumOfSquares(int n) { long total = 0L; for (int i = 1; i <= n; i++) { total += (long) i i; } return total; }. Without a loop you can use a primitive stream: LongStream.rangeClosed(1, n).map(i -> i i).sum(), which never creates Long objects.
Exercise
Which of these allocates wrapper objects per element, and what is the primitive alternative? (1) Function<Integer, Integer> f = x -> x + 1; (2) Optional<Double> avg = list.stream().mapToDouble(d -> d).average() followed by conversion to Optional<Double>; (3) List<Integer> data = new ArrayList<>().
Show answer
(1) boxes the argument and the result on every call; use IntUnaryOperator. (2) average() already returns OptionalDouble, which holds a primitive; converting it to Optional<Double> adds a box, so keep the OptionalDouble. (3) boxes every element; use int[] if the size is fixed, or a primitive collection library if the data is large and hot. For a small list that is not performance-critical, keeping List<Integer> is acceptable.