lazy evaluation - Laziness in Swift -
why lazy
used here?
extension sequencetype { func mapsome<u>(transform: generator.element -> u?) -> [u] { var result: [u] = [] case let x? in lazy(self).map(transform) { result.append(x) } return result } }
this extension takes transformation function returns optional, , returns array of values weren’t transformed nil
why not use self.map(transform)
? laziness necessary here?
it avoids creation of intermediate array.
self.map(transform)
returns array containing results of transformation of all sequence elements, traversed build resulting array non-nil elements.
lazy(self).map(transform)
is sequence of transformed elements, iterated on non-nil elements. transformed elements computed during enumeration. (each call next()
on lazy sequence produces 1 element transforming next element of original sequence.)
both methods work. lazy method perform better large sequences, can depend on many factors (the size of array, whether elements value or reference types, how costly copy array elements etc). small arrays lazy method slower due additional overhead. in concrete application, profiling instruments decide method use.
Comments
Post a Comment