Java 8流运行速度比for循环慢的关键指标? [英] Key indicators that a Java 8 stream will run slower than a for loop?

查看:332
本文介绍了Java 8流运行速度比for循环慢的关键指标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数情况下,Java 8流允许的代码比旧式循环更具可读性。但是,根据我自己的经验和我所读到的内容,使用流而不是for循环可能会导致性能损失(或偶尔会有改进),有时难以预测。



在一个大型项目中,为每个循环编写基准测试似乎不可行,所以在决定是否替换 for 循环时一个流,关键因素是什么(例如,预期的集合大小,通过过滤删除的值的预期百分比,迭代操作的复杂性,减少或聚合的类型等)哪些可能是否会产生性能变化?



注意:这是我之前提出的问题,由于过于宽泛而被关闭(以及并行流的各个方面)很好地涵盖了< a href =https://stackoverflow.com/questions/20375176/should-i-always-use-a-parallel-stream-when-possible/23370799#23370799>另一个SO问题),所以让我们把它限制为顺序流。

解决方案

这不仅为每个人编写基准测试都不可行循环,它反效果。特定的,特定于应用程序的循环在进入微基准时可能会完全不同。



对于实际应用程序,标准优化规则适用: don不这样做。只需编写更易读的内容,只有存在性能问题时,才能整个应用程序来检查特定的循环或流是否确实是瓶颈。只有在这种情况下,您可以尝试在特定瓶颈的两个习语之间切换,看看它是否有所作为。



在大多数情况下,它不会。如果存在真正的性能问题,那么它将取决于操作类型,例如:使用 O(n²)时间复杂度等执行嵌套迭代。此类问题不取决于您是否使用 Stream for 循环,这两个习语之间的微小性能差异不会改变代码缩放的方式。


Java 8 streams allow code that is a lot more readable than old-fashioned for loops, in most cases. However, based on my own experience and what I've read, using a stream instead of a for loop can involve a performance hit (or occasionally an improvement) which is sometimes difficult to predict.

In a large project it doesn't seem feasible to write a benchmark test for every loop, so when deciding whether to replace a for loop with a stream, what are the key factors (e.g. expected size of the collection, expected percentage of values removed by filtering, complexity of iterative operations, the type of reduction or aggregation, etc.) which give a likely indication of the performance change that will result?

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

解决方案

It’s not only "not feasible to write a benchmark test for every loop", it’s counter productive. A particular, application specific loop may perform entirely different when being put into a micro-benchmark.

For an actual application, the standard rule of optimization applies: don’t do it. Just write whatever is more readable and only if there is a performance problem, profile the entire application to check whether a particular loop or stream use really is the bottleneck. Only if this is the case, you may try to switch between both idioms at the particular bottleneck to see whether it makes a difference.

In most cases, it won’t. If there is a real performance issue, it will stem from the type of operation, e.g. performing a nested iteration with an O(n²) time complexity, etc. Such problems do not dependent on whether you use a Stream or a for loop and the minor performance differences between these two idioms don’t change how your code scales.

这篇关于Java 8流运行速度比for循环慢的关键指标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆