Laziness in Swift

后端 未结 2 1617
刺人心
刺人心 2021-02-03 13:23

Why is lazy used here?

extension SequenceType {
    func mapSome(transform: Generator.Element -> U?) -> [U] {
        var result: [U]         


        
2条回答
  •  天涯浪人
    2021-02-03 13:46

    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.

提交回复
热议问题