It looks like stream.parallel processing works slower than stream.sequential one - for the stream with a big amount of data. And speed of stream processing without explicit pointing the method is between sequential and parallel. Why?
package com.jsp; import java.util.Random; import java.util.stream.Stream; public class Test01 { enum Method { Default, Sequential, Parallel, SummaryStats } public static void main(String[] args) { long count = 30_000_000L; for (var method: Method.values()) { System.out.println(m + ": " + test(count, method)); } } private static double test(long count, Method method) { // init stream with random values var r = new Random(); Stream<Integer> s = Stream .iterate(r.nextInt(), prev -> r.nextInt()) .limit(count); // estimate speed of processing method var t1 = System.nanoTime(); switch(method) { case Sequential -> s.sequential().reduce(Integer::max); case Parallel -> s.parallel().reduce(Integer::max); case SummaryStats -> s.mapToInt(Integer::intValue).summaryStatistics(); default -> s.reduce(Integer::max); } var t2 = System.nanoTime() - t1; return (double) t2 / 1000000000; } } The output of this code is:
Default: 0.3314137 Sequential: 0.26828490 Parallel: 1.1365678 SummaryStats: 0.4159758 - HW: Huawei Matebook D14, AMD Ryzen 5 4500U, 8 Gb RAM
- SW: Windows 10 x64 22H2 Home Edition, Oracle OpenJDK 21