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

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

问题描述

有时你想用多个条件过滤Stream:

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

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

或者你可以用一个复杂的条件和一个 single filter 来做同样的事情:

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.

组合两个过滤器实例会创建更多的对象,因此会创建更多的委托代码,但如果您使用方法引用而不是 lambda 表达式,这可能会改变,例如将 filter(x -> x.isCool()) 替换为 filter(ItemType::isCool).这样,您就消除了为 lambda 表达式创建的合成委托方法.因此,与使用带有 && 的 lambda 表达式的单个 filter 调用相比,使用两个方法引用组合两个过滤器可能会创建相同或更少的委托代码.

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 &&.

但是,如上所述,这种开销会被 HotSpot 优化器消除并且可以忽略不计.

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¹.

所以没有简单的答案.

最重要的是,不要考虑低于气味检测阈值的性能差异.使用更具可读性的内容.

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

¹...并且需要一个实现对后续阶段进行并行处理,这是标准 Stream 实现目前未采用的方法

¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation

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

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