为什么Java 8中的IntStream.range(0,n)不应该并行? [英] Why IntStream.range(0,n) in Java 8 shouldn't be parallel?

查看:54
本文介绍了为什么Java 8中的IntStream.range(0,n)不应该并行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过一本有关Java 8的书,书上说使用并行流通过 IntStream.range(0,someNumber)获取数字范围可能比顺序的慢...为什么?

I've read a book on Java 8 and the book says that using parallel streams in order to get range of numbers via IntStream.range(0,someNumber) can be slower than sequential one...why is that?

推荐答案

它可能会更慢.默认情况下,您应该始终使用顺序流.与顺序流相比,并行流的开销要高得多,因为它需要在内部进行大量协调工作以及某些簿记活动.

It can be slower. You should always use sequential streams by default. A parallel stream has a much higher overhead compared to a sequential one as it needs a lot of coordination efforts internally along with certain book keeping activities.

如果满足以下条件,则应考虑使用并行的:1.您要处理大量项目,每个项目都需要花费大量时间,并且可以并行化.2.如果您首先遇到性能问题.因此,在尝试并行流或任何其他并发构造之前,黄金法则始终是基准.

You should consider parallel ones if: 1. You have a huge amount of items to process and each item takes substantial time and can be parallelized. 2. If you have for a performance problem in first place. So golden rule is always benchmark before trying parallel streams or any other concurrency constructs.

在您的情况下,如果范围很小,那么在这种情况下,与并行流相关的开销可能会覆盖您应该获得的收益.还要检查这篇文章: http://zeroturnaround.com/rebellabs/java-parallel-streams-for-your-health-bad-for-your-health/

In your case if the range is very small then in that case overhead associated with parallel streams can override the benefit you are supposed to get. Also check this article: http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/

这篇关于为什么Java 8中的IntStream.range(0,n)不应该并行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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