Java Reference
In-Depth Information
Note that the results should be taken with a grain of salt. Many factors will influence the
execution time, such as how many cores your machine supports! You can try this on your own
machine by running the code available on the topic's repository. Executing it on a MacBook pro
Intel i7 2.3 GHz quad-core, it prints the following:
Sequential sum done in: 97 msecs
You should expect that the iterative version using a traditional for loop runs much faster
because it works at a much lower level and, more important, doesn't need to perform any boxing
or unboxing of the primitive values. If you try to measure its performance with
System.out.println("Iterative sum done in: " +
measureSumPerf(ParallelStreams::iterativeSum, 10_000_000) + " msecs");
you'll obtain
Iterative sum done in: 2 msecs
Now let's do the same with the parallel version of that function
System.out.println("Parallel sum done in: " +
measureSumPerf(ParallelStreams::parallelSum, 10_000_000) + " msecs" );
and see what happens:
Parallel sum done in: 164 msecs
This is quite disappointing: the parallel version of the summing method is much slower than the
sequential one. How can you explain this unexpected result? There are actually two issues mixed
together:
iterate generates boxed objects, which have to be unboxed to numbers before they can be added.
iterate is difficult to divide into independent chunks to execute in parallel.
The second issue is particularly interesting because you need to keep a mental model that some
stream operations are more parallelizable than others. Specifically, the iterate operation is hard
to split into chunks that can be executed independently because the input of one function
application always depends on the result of the previous application, as illustrated in figure 7.2 .
 
Search WWH ::




Custom Search