Java streams vs for loops: 4.4 ms vs 4.5 ms (boxing costs 6.5 ms)
Are Java streams slower than for loops?
Not for primitives. Summing the squares of the even numbers in 5 million ints took 4.4 ms with a for loop, 4.5 ms with an IntStream and 6.5 ms with a boxed Stream<Integer> on JDK 17; boxing, not streams, was the cost.
Results
| for loop over int[] | 4.4 ms |
|---|---|
| IntStream over int[] | 4.5 ms |
| Stream<Integer> over List | 6.5 ms |
How it was measured
5,000,000 integers, best of 30 rounds, each variant in its own method so the JIT compiles it normally.
for (int v : arr) if (v % 2 == 0) s += (long) v * v;
Arrays.stream(arr).filter(v -> v % 2 == 0).mapToLong(v -> (long) v * v).sum();Why
Primitive streams avoid boxing and inline well. Boxed streams allocate wrapper objects and chase pointers.
When this does not apply
Micro-benchmarks mislead. Use JMH and profile real code before choosing between styles.
Environment
MacBook Air (Apple silicon, 8 cores), macOS, JDK 17. Measured 2026-10-12.
Source: shorts/demo-ticket/java/Streams.java in my content-engine repository. Treat any single run as a direction; re-run it on your hardware.
Related
By Josué Barros, senior software engineer (full-stack, data and AI).