I'm testing parallel streams and I've found this strange (to me) result. In my test:
final int MIL = 1000000;
IntStream s;
s = IntStream.rangeClosed(1, MIL);
long start = System.nanoTime();
s.filter(i -> i % 11 == 0)
.map(i -> i % 3)
.reduce(0, (subtotal, element) -> subtotal + element);
long end = System.nanoTime();
System.out.println("NON PARALLEL reduce: " + (end - start));
s = IntStream.rangeClosed(1, MIL);
long startP = System.nanoTime();
s.parallel().filter(i -> i % 11 == 0)
.map(i -> i % 3)
.reduce(0, (subtotal, i) -> subtotal + i);
long endP = System.nanoTime();
System.out.println(" PARALLEL reduce: " + (endP - startP));
I get the following result:
NON PARALLEL reduce: 10156400
PARALLEL reduce: 31094100
that is the parallel stream is considerably slower. Why? If I susbstitute reduce() with sorted(), the result is opposite: parallel stream is significantly faster.