Java 8流:多个过滤器与复杂的条件 [英] Java 8 Streams: multiple filters vs. complex condition

查看:2098
本文介绍了Java 8流:多个过滤器与复杂的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,您想过滤一个 Stream 多个条件:

  myList.stream()。filter(x  - > x.size()> 10).filter(x  - > x.isCool())... 

或者您可以对复杂的条件和单个 过滤器

  myList.stream()。filter(x  - > x.size()> 10& & x  - > x.isCool())... 

方法有更好的性能特点,但是我不知道它。

第一种方法赢得可读性,但是性能更好?

解决方案

这两个选项必须执行的代码非常相似,以至于无法可靠地预测结果。底层的对象结构可能会有所不同,但这对热点优化器来说并不是什么挑战。因此,这取决于其他周围的条件,如果有任何区别,会产生更快的执行。



结合两个过滤器实例创建更多的对象,因此更多的委托代码,但是这可以改变,如果你使用方法引用而不是lambda表达式,例如通过 filter(ItemType :: isCool)来替换 filter(x - > x.isCool())。这样你就消除了为你的lambda表达式创建的综合委托方法。因此,使用两个方法引用来组合两个过滤器可能会创建相同或较少的委托代码,而不是使用&& <>的lambda表达式来执行单个过滤器 / code>。



但是,正如所说,这种开销将被HotSpot优化器消除,可以忽略不计。

从理论上讲,两个过滤器可能比单个过滤器更容易并行化,但是这只与计算量较大的任务有关。

所以没有简单的答案。

底线是,不要考虑低于气味检测阈值的性能差异。使用更可读的。


Sometimes you want to filter a Stream with more than one condition:

myList.stream().filter(x -> x.size() > 10).filter(x -> x.isCool()) ...

or you could do the same with a complex condition and a single filter:

myList.stream().filter(x -> x.size() > 10 && x -> x.isCool()) ...

My guess is that the second approach has better performance characteristics, but I don't know it.

The first approach wins in readability, but what is better for the performance?

解决方案

The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.

Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool()) by filter(ItemType::isCool). That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter invocation using a lambda expression with &&.

But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.

In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks.

So there is no simple answer.

The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.

这篇关于Java 8流:多个过滤器与复杂的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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