Key indicators that a Java 8 thread will be slower than a for loop?

Java 8 threads make it possible in most cases to use code that is much more readable than old-fashioned for loops. However, based on my own experience and what I read, using a thread instead of a for loop can lead to performance loss (or sometimes to improvement), which is sometimes difficult to predict.

In a large project, it is not possible to write a test test for each cycle, so when deciding whether to replace the for cycle with a stream, what are the key factors (for example, the expected size of the collection, the expected percentage of values ​​deleted by filtering, the complexity of iterative operations, the type of reduction or aggregation, etc. e.) that provide a likely indication of a change in performance that will result?

Note: this is a narrowing of my earlier question , which was closed to too broad (and for which aspects of parallel threads were pretty well covered in another SO question ), so let me just limit this to sequential threads.

+5
source share
2 answers

It’s not only “it’s not possible to write a test test for each cycle”, but its counter is effective. The specific circuit specific to the application may be completely different when it is introduced into the micro benchmark.

For a real application, the standard optimization rule applies: do not do this. Just write what is more readable, and only if there is a performance problem, profile the entire application to see if a particular loop or streaming usage is really a bottleneck. Only if this is the case, can you try switching between idioms in a particular bottleneck to see if the difference matters.

In most cases, it will not. If there is a real performance issue, it will be related to the type of operation, for example. performing a nested iteration with a time complexity of O(n²) , etc. Such issues are independent of whether you use a Stream or for loop, and slight performance differences between the two idioms do not change how your code scales.

+19
source

There are no large common speed differences between streams and loops , their advantages / disadvantages are specific to a particular task. Regardless of whether you choose one or the other, it should depend (mainly) on the readability of the code. For some performance comparisons, see Benchmark1 and Benchmark2 , where you can see Brian Goetz's comment on one of the answers:

Your conclusion about performance, although valid, is bloated. There are many cases where the stream code is faster than the iterative code, largely because the costs of accessing elements are cheaper with streams than with regular iterators. And in many cases, the version of threads comes down to what is equivalent to the handwritten version. Of course, the devil is in the details; any bit of code can behave differently.

Also, just make sure you use JMH when testing.

+6
source

Source: https://habr.com/ru/post/1239984/


All Articles