问题描述
在随后应用诸如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文档:
因此,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
是专门为与这些方法的链一起使用而设计的,因此对于a的理解已被废止了.不需要其他方法(例如forall
/exists
),因此尚未将它们添加到withFilter
的FilterMonadic
返回类型中.
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
.
这篇关于withFilter而不是filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!