Laziness in Swift

后端 未结 2 1618
刺人心
刺人心 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.

    0 讨论(0)
  • 2021-02-03 13:49

    It avoids the creation of an intermediate array.

    self.map(transform)
    

    returns an array containing the results of the transformation of all sequence elements, which would then be traversed to build the resulting array with the non-nil elements.

    lazy(self).map(transform)
    

    is a sequence of the transformed elements, which is then iterated over to get the non-nil elements. The transformed elements are computed during the enumeration. (Each call to next() on the lazy sequence produces one element by transforming the next element of the original sequence.)

    Both methods work. The lazy method would probably perform better for large sequences, but that can depend on many factors (the size of the array, whether the elements are value or reference types, how costly it is to copy array elements etc). For small arrays the lazy method would probably be slower due to the additional overhead. In a concrete application, profiling with Instruments would help to decide which method to use.

    0 讨论(0)
提交回复
热议问题