Why does this parallel stream run 15x SLOWER?

Viewed 506

I was attempting to demonstrate to a Java novice streams and such. He said he had read that streams can be slower than for loops for primitive types. So, I set immediately to prove that wrong! What I got was a shock!

The for-loop and the serial stream run roughly the same, but the parallel stream is consistently and dramatically slower. Can someone explain why?

   @Test
    public void foo() throws Exception {

        Random r = new Random();

        IntSummaryStatistics stats = new IntSummaryStatistics();

        long start = System.currentTimeMillis();
        for(int i = 0; i < 100000000;i++) {
            stats.accept(r.nextInt() * 2);
        }
        System.out.println(System.currentTimeMillis() - start);

        start = System.currentTimeMillis();
        stats = r.ints(100000000).map(rn -> rn * 2).summaryStatistics();
        System.out.println(System.currentTimeMillis() - start);

        start = System.currentTimeMillis();
        stats = r.ints(100000000).parallel().map(rn -> rn * 2).summaryStatistics();
        System.out.println(System.currentTimeMillis() - start);


    }

resutls:

1067
1047
15184
0 Answers
Related