I experienced a performance issue when using the stream created using the spliterator() over an Iterable. ie., like StreamSupport.stream(integerList.spliterator(), true). Wanted to prove this over a normal collection. Please see below some benchmark results.
Question: Why does the parallel stream created from an iterable much slower than the stream created from an ArrayList or an IntStream ?
From a range
public void testParallelFromIntRange() { long start = System.nanoTime(); IntStream stream = IntStream.rangeClosed(1, Integer.MAX_VALUE).parallel(); System.out.println("Is Parallel: "+stream.isParallel()); stream.forEach(ParallelStreamSupportTest::calculate); long end = System.nanoTime(); System.out.println("ParallelStream from range Takes : " + TimeUnit.MILLISECONDS.convert((end - start), TimeUnit.NANOSECONDS) + " milli seconds"); } Is Parallel: true
ParallelStream from range Takes : 490 milli seconds
From an Iterable
public void testParallelFromIterable() { Set<Integer> integerList = ContiguousSet.create(Range.closed(1, Integer.MAX_VALUE), DiscreteDomain.integers()); long start = System.nanoTime(); Stream<Integer> stream = StreamSupport.stream(integerList.spliterator(), true); System.out.println("Is Parallel: " + stream.isParallel()); stream.forEach(ParallelStreamSupportTest::calculate); long end = System.nanoTime(); System.out.println("ParallelStream from Iterable Takes : " + TimeUnit.MILLISECONDS.convert((end - start), TimeUnit.NANOSECONDS) + " milli seconds"); } Is Parallel: true
ParallelStream from Iterable Takes : 12517 milli seconds
And the so trivial calculate method.
public static Integer calculate(Integer input) { return input + 2; }
ContinguousSetactually have properspliterator? Guava is not optimised for Java 8 whereas the JDK obviously is.ContiguousSet.spliterator()return a sized spliterator, or one of unknown size? That might affect how the data is split among threads. You can useSpliterators.spliterator(Iterator, long, int)to create a spliterator from an iterator and the size of the set.hasNext/next.