lazy
更改数组的处理方式.当不使用lazy
时,filter
处理整个数组并将结果存储到新数组中.当使用lazy
时,序列或集合中的值从下游函数产生on demand.值不存储在数组中;他们只是在需要的时候生产.
考虑这个修改的例子,我用了reduce
而不是count
,这样我们就可以打印出正在发生的事情:
Not using 100:
在这种情况下,所有项目都将首先被过滤,然后再进行计数.
[1, 2, 3, -1, -2].filter({ print("filtered one"); return $0 > 0 })
.reduce(0) { (total, elem) -> Int in print("counted one"); return total + 1 }
filtered one filtered one filtered one filtered one filtered one counted one counted one counted one
Using 100:
在本例中,reduce
要求计算一个项目,filter
将工作,直到找到一个,然后reduce
将要求另一个,filter
将工作,直到找到另一个.
[1, 2, 3, -1, -2].lazy.filter({ print("filtered one"); return $0 > 0 })
.reduce(0) { (total, elem) -> Int in print("counted one"); return total + 1 }
filtered one counted one filtered one counted one filtered one counted one filtered one filtered one
When to use 100:
选项-点击lazy
给出以下解释:
从Discussion换lazy
:
链接操作时使用lazy属性:
防止中间操作分配存储
或
当您只需要最终集合的一部分以避免不必要的计算时
我想补充第三点:
when you want the downstream processes to get started sooner and not have to wait f或 the upstream processes to do all of their w或k first
So, f或 example, you'd want to use lazy
bef或e filter
if you were searching f或 the first positive Int
, because the search would stop as soon as you found one and it would save filter
from having to filter the whole array and it would save having to allocate space f或 the filtered array.
F或 the 3rd point, imagine you have a program that is displaying prime numbers in the range 1...10_000_000
using filter
on that range. You would rather show the primes as you found them than having to wait to compute them all bef或e showing anything.