0

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.

Pier Luigi
  • 7,871
  • 9
  • 36
  • 46
  • Have you compared the speed for different range sizes. A few additional data points will most likely show that at larger ranges, parallelisation will win in the end. – toolkit Mar 09 '20 at 10:30

1 Answers1

1

Running your code on my 8(4) cores CPU, parallel is faster by 25-35%. Parallel functioning behind the scenes is a multithreading. Initializing and synchronizing threads are time efficient. Speed belongs to what do you do with your stream data, and also your CPU on what you runs the code.

szeak
  • 325
  • 1
  • 7