Home > Back-end >  Time difference between forEach() and forEachOrdered in parallel stream
Time difference between forEach() and forEachOrdered in parallel stream

Time:11-14

I made the following code.

    @Test
    public void parallelStream() {
        IntStream.rangeClosed(0,10_000).boxed().parallel()
                        .forEach(System.out::println);
    }

    @Test
    public void parallelStreamOrdered() {
        IntStream.rangeClosed(0,10_000).boxed().parallel()
                .forEachOrdered(System.out::println);
    }

As a result of the performance, parallelStream took 178 ms and parallelStreamOrder took 33 ms.

I know that in parallel, .forEach() is non-deterministic, and .forEachOrdered() is guaranteed order.

But is it related to speed? It was expected that keeping the order would slow down the speed. I wonder why the speed is so different.

CodePudding user response:

10_000 is a very small number to make a proper test. Try 10_000_000 instead.

On my laptop, parallelStreamOrdered took 30 seconds, while parallelStream took about 5 seconds.

CodePudding user response:

I think you should test this with some big value then the result would be much more clear and there will be a high time difference.

  • Related