Java Stream vs For Loop: Which Is Faster? A Performance Benchmark
This article benchmarks Java 8 Stream against traditional for‑loops across primitive, object, and complex‑object scenarios, revealing that while for‑loops excel on simple primitive tasks, parallel Stream often outperforms both sequential Stream and loops, especially on multi‑core systems.
As a developer, mastering new knowledge is essential; Java 8 Stream is a powerful feature that can both simplify code and boost performance.
This article conducts performance tests to compare for‑loop, sequential Stream and parallel Stream on different data types.
Test Environment
JDK 1.8.0_151
MacBook Pro i7, 16 GB RAM
Testing tools: junitperf and JUnit
IDE: IntelliJ IDEA
Experiment 1 – Primitive int iteration
Initialize an int array with 500 million random numbers and find the minimum value using three methods: testIntFor (for‑loop), testIntStream (sequential Stream) and testIntParallelStream (parallel Stream).
public class StreamTest {
public static int[] arr;
@BeforeAll
public static void init() {
arr = new int[500000000];
randomInt(arr);
}
@JunitPerfConfig(duration = 10000, warmUp = 1000, reporter = {HtmlReporter.class})
public void testIntFor() { minIntFor(arr); }
@JunitPerfConfig(duration = 10000, warmUp = 1000, reporter = {HtmlReporter.class})
public void testIntParallelStream() { minIntParallelStream(arr); }
@JunitPerfConfig(duration = 10000, warmUp = 1000, reporter = {HtmlReporter.class})
public void testIntStream() { minIntStream(arr); }
private int minIntStream(int[] arr) { return Arrays.stream(arr).min().getAsInt(); }
private int minIntParallelStream(int[] arr) { return Arrays.stream(arr).parallel().min().getAsInt(); }
private int minIntFor(int[] arr) {
int min = Integer.MAX_VALUE;
for (int anArr : arr) {
if (anArr < min) { min = anArr; }
}
return min;
}
private static void randomInt(int[] arr) {
Random r = new Random();
for (int i = 0; i < arr.length; i++) { arr[i] = r.nextInt(); }
}
}Results (images) show that sequential Stream is about twice as slow as the for‑loop, while parallel Stream is roughly half the time of the for‑loop.
Experiment 2 – Object (String) iteration
Generate a List of 10 million random strings and find the minimum string using the same three approaches. The performance gap between for‑loop and sequential Stream narrows (about 1.25×), and parallel Stream outperforms both, taking less than half the for‑loop time.
Experiment 3 – Complex object reduction
Create a List of 1 million User objects, each containing a username and a distance value, then aggregate total distance per user using Stream.
// sequential
users.stream().collect(
Collectors.groupingBy(User::getUserName,
Collectors.summingDouble(User::getMeters)));
// parallel
users.parallelStream().collect(
Collectors.groupingBy(User::getUserName,
Collectors.summingDouble(User::getMeters)));Images of the results indicate that both sequential and parallel Stream are faster than the for‑loop, with parallel Stream showing the greatest advantage, especially as CPU cores increase.
Conclusion
For simple primitive iteration, a classic for‑loop is fastest; parallel Stream can beat it on multi‑core machines.
For more complex operations, Stream (especially parallel) matches or exceeds for‑loop performance.
When multiple filtering and reduction steps are involved, Stream provides clearer code and superior speed.
Overall, use a for‑loop for trivial tasks and prefer Stream for complex data processing.
Recommended tool: junitperf (https://github.com/houbb/junitperf) for Java performance testing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
