lazy
changes the way the array is processed. When lazy
is not used, filter
processes the entire array and stores the results into a new array. When lazy
is used, the values in the sequence or collection are produced on demand from the downstream functions. The values are not stored in an array; they are just produced when needed.
Consider this modified example in which I've used reduce
instead of count
so that we can print out what is happening:
Not using lazy
:
In this case, all items will be filtered first before anything is counted.
[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 lazy
:
In this case, reduce
is asking for an item to count, and filter
will work until it finds one, then reduce
will ask for another and filter
will work until it finds another.
[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 lazy
:
option-clicking on lazy
gives this explanation:
From the Discussion for lazy
:
Use the lazy property when chaining operations:
to prevent intermediate operations from allocating storage
or
when you only need a part of the final collection to avoid unnecessary computation
I would add a third:
when you want the downstream processes to get started sooner and not have to wait for the upstream processes to do all of their work first
So, for example, you'd want to use lazy
before filter
if you were searching for 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 for the filtered array.
For 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 before showing anything.
lazy
initialization is usually use for heavy elements like UIKit elements. Haven't seen it being used with arrays. – Marigolda