用过滤器代替过滤器 [英] withFilter instead of filter
问题描述
在之后应用 map、flatmap 等函数时,使用 withFilter 而不是 filter 总是更高效吗?
Is it always more performant to use withFilter instead of filter, when afterwards applying functions like map, flatmap etc.?
为什么只支持 map、flatmap 和 foreach?(预期的功能,如 forall/exists 以及)
Why are only map, flatmap and foreach supported? (Expected functions like forall/exists as well)
推荐答案
来自 Scala 文档:
注意:c filter p
和 c withFilter p
的区别在于前者创建一个新的集合,而后者只限制域后续的map
、flatMap
、foreach
和withFilter
操作.
Note: the difference between
c filter p
andc withFilter p
is that the former creates a new collection, whereas the latter only restricts the domain of subsequentmap
,flatMap
,foreach
, andwithFilter
operations.
所以 filter
将获取原始集合并生成一个新集合,但是 withFilter
将非严格地(即懒惰地)将未过滤的值传递给以后的 map
/flatMap
/withFilter
调用,保存第二次通过(过滤的)集合.因此在传递到这些后续方法调用时会更有效率.
So filter
will take the original collection and produce a new collection, but withFilter
will non-strictly (i.e. lazily) pass unfiltered values through to later map
/flatMap
/withFilter
calls, saving a second pass through the (filtered) collection. Hence it will be more efficient when passing through to these subsequent method calls.
事实上,withFilter
是专门为处理这些方法链而设计的,这就是理解的脱糖.不需要其他方法(例如forall
/exists
),因此它们没有被添加到FilterMonadic
返回类型中>withFilter.
In fact, withFilter
is specifically designed for working with chains of these methods, which is what a for comprehension is de-sugared into. No other methods (such as forall
/exists
) are required for this, so they have not been added to the FilterMonadic
return type of withFilter
.
这篇关于用过滤器代替过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!