Laziness in Swift

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

提交回复
热议问题