Video in progress

Strong Middle 🌊 Streams and lambdas

How much does boxing affect stream performance, and how do you reduce it?

Every number in a Stream<Integer> is an Integer object on the heap (outside the -128..127 cache). At large volume that means many allocations, GC load and pointer chasing. Primitive variants like mapToInt/IntStream, comparingInt and summingLong remove that cost.

📖 Answer

Where boxing hides:

// boxing/unboxing at every step
long sum = orders.stream().map(Order::amount).reduce(0L, Long::sum);

// primitive: no objects are created
long sum2 = orders.stream().mapToLong(Order::amount).sum();

Other typical places:

  • Comparator.comparing(Order::amount): boxing on every comparison; use comparingLong;
  • Collectors.summingInt and averagingDouble keep a primitive inside, but reducing(0, ..., Integer::sum) doesn't;
  • IntStream.range(...).boxed().collect(...): don't call boxed() if you don't have to;
  • counting into a Map<Long, Long>: every key and value is an object.

How noticeable is it? With a few hundred elements, not at all, and the JIT's escape analysis sometimes removes the allocation itself. In an analysis of millions of elements or on a hot endpoint the difference can reach several times. Don't guess: measure with JMH, and if Long.valueOf / Integer.valueOf show up a lot in a profile (async-profiler allocation mode, JFR), that's the signal.

At very large volume, primitive collections (Eclipse Collections, fastutil) are an option too, but that means adding a separate dependency. Usually moving to primitive streams is enough.