Video in progress
Are streams slower than a plain for loop? If someone on the team says "streams are slow, we write for everywhere", what do you say?
In a small pipeline a stream has some extra overhead (lambdas, pipeline objects), but the JIT often narrows the gap, and in a real service it is invisible next to DB or network time. It isn't a general rule: on a specific hot path, decide by measuring with JMH.
📖 Answer
There is truth on both sides.
What costs extra in a stream:
- several objects per pipeline (stages, sinks, spliterators);
- allocation for values captured by lambdas;
- the inlining depth limit is reached quickly: in very long chains the JIT can't inline everything;
- boxing in
Stream<Integer>: that's the biggest source of difference, not the stream itself.
But in practice:
- filtering a list of 100 elements takes nanoseconds; a single SQL query takes milliseconds;
- on primitive streams and simple pipelines, after JIT the difference is often within a few percent;
- a badly written
foris slow too.
If you need to measure, don't use System.currentTimeMillis(): warmup, dead code elimination and OSR distort the picture:
@State(Scope.Benchmark)
public class SumBench {
int[] data = new Random(42).ints(1_000_000).toArray();
@Benchmark public long loop() {
long s = 0;
for (int v : data) if (v > 0) s += v;
return s;
}
@Benchmark public long stream() {
return Arrays.stream(data).filter(v -> v > 0).asLongStream().sum();
}
}
My answer to the team: the default is whichever variant reads most clearly. Often that's a stream, sometimes (especially if you need an index, a break or several accumulators) a plain for. If a profiler (async-profiler, JFR) shows a particular loop is hot, we measure and optimize that spot. A rule of "streams are banned" across the whole codebase doesn't help.
Sign up to mark studied questions and save your progress.