Java: Curious case of parallelStream() being slower than stream()!

Hemanth Gopi
2 min readJun 19, 2020

--

The curious case of why the code using “parallelStream()” appears to be slower at times than those using “stream()”.

There are several problems in using parallelStream(), as it were.
Foremost being parallelStream() always involves performing more actual work than by doing it sequentially [ i.e stream() ].

Splitting the work among several threads and merging or combining the results involves significant overhead. Use cases like transforming short strings to lower-case strings are tiny enough that they become negligible when compared to the parallel splitting overhead.

Process the data using multiple threads can have some initial setup costs, e.g. initializing the thread pool. These costs may suppress the gain obtained from using those threads, especially if the runtime is already quite low. Additionally, if there are other threads running, background processes, etc., or contention is high then the performance of parallel processing can reduce further.

Stream implementation in Java is by default sequential unless it is explicitly mentioned in parallel. When a stream is executed as parallel, then the Java runtime partitions the stream into multiple sub-streams. Aggregate operations process these sub-streams by iterating over them in parallel and then combine those results. So, Parallel Streams can be used in areas where the Sequential Streams have performance implications

These issues exist for a long time in the parallel world [ You saw what I did there, ‘Parallel processing world’]. This article gives some details in the light of Java 8 parallel() and some more interesting stuff: http://java.dzone.com/articles/think-twice-using-java-8

--

--

Hemanth Gopi

Software Engineer 2 @ PayPal | Ex Zoho. Graphic Design hobbyist. Interested in Financial Maths and Economics.