Why is lazy
used here?
extension SequenceType {
func mapSome(transform: Generator.Element -> U?) -> [U] {
var result: [U]
As Martin R mentioned lazy()
avoids the creation of an intermediate array. However if I compare the execution time of the function on arrays of different sizes you find that lazy()
is "only" 10% faster.
Interestingly, you find that lazy()
is for arrays with less than 200 elements up to 2 times as fast and gets with more elements almost equally fast as the function without the conversion (10% faster).
(Tested with Xcode 6.4 and Xcode 7 with global functions and protocol extension in a Playground as (compiled) source files)
So lazy()
would rather be used for Sequences
where you don't know if it is finite. Then, for loops are likely used with break
or return
:
for element in lazy(sequence).map{ ... } {
if element == 1000 {
break
}
// use element
}
If you call map on a infinite Sequence
(like 1,2,3...) the execution would also be infinite. With lazy()
the transformation and the execution get "delayed" thus you can handle "big" and infinite sequences more efficiently if you break out of the loop before the last element.