Why does this parallel stream run 15x SLOWER? [duplicate]

风格不统一 提交于 2019-12-10 10:23:08

问题


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

来源:https://stackoverflow.com/questions/44294483/why-does-this-parallel-stream-run-15x-slower

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!