简体   繁体   English

我什么时候应该去Java-8 Streams?

[英]When should I go for Java-8 Streams?

I've started learning Java-8 streams lately. 我最近开始学习Java-8流。 I'm looking at a huge code base and trying to figure out where can I use streams to improve performance. 我正在寻找一个庞大的代码库,并试图找出在哪里可以使用流来提高性能。

From what I've understood, replacing every loop with streams doesn't make sense as streams are not always better than loops. 根据我的理解,用流替换每个循环都没有意义,因为流并不总是优于循环。 Following are few cases I've understood to be beneficial: 以下几个案例我认为是有益的:

  1. Where only certain elements in a collection results in more computation. 只有集合中的某些元素会导致更多的计算。
 while(iterate over a collection) { if(certain condition is met) { //do some computation } else { //do nothing } } 

Using streams here avoids loading the needless members of the collection here. 在这里使用流可以避免在这里加载集合中不必要的成员。 (faster & memory efficient) (更快,更高效)

  1. when we want to collect results in a collection where the resultant order doesn't matter and each iteration is independent (Stateless). 当我们想要在集合中收集结果时,结果顺序无关紧要,每次迭代都是独立的(无状态)。 If computation is CPU-intensive and we use parallel streams here, I believe it will be more performant. 如果计算是CPU密集型的,我们在这里使用并行流,我相信它会更高效。

Please correct me if I'm wrong. 如果我错了,请纠正我。 I'm looking for more such cases... 我正在寻找更多此类案例......

Going back over a codebase and rewriting things by hand is probably a waste of time. 回到代码库并手工重写事情可能是浪费时间。 Generally speaking, streams aren't going to provide a performance benefit unless you're using parallel streams over a very large computation (see http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html for detailed advice). 一般来说,除非您在非常大的计算中使用并行流,否则流不会提供性能优势(有关详细建议,请参阅http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html ) 。 Most of the time, streams will have ~equal performance; 大多数情况下,流将具有相同的性能; they'll just be shorter to write. 他们写的时间会更短。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM