UNKO.fun

Blog Post

Swift集合中的lazy属性

October 5, 2018 | 3 min

swift

Post content

lazy属性

这里lazy不是关键字,而是Collection协议里的一个属性,下面给出该属性的注释。

/// A view onto this collection that provides lazy implementations of
/// normally eager operations, such as `map` and `filter`.
///
/// Use the `lazy` property when chaining operations to prevent
/// intermediate operations from allocating storage, or when you only
/// need a part of the final collection to avoid unnecessary computation.

这里说了,使用该属性会让链式调用的中间环节不开辟新的内存空间。

下面我们简单试验一下在十万级别下使用lazy属性与否的性能差异

/// 我们准备了一个1-10w的数组
let first = nums.lazy.map{$0 + 1}.filter{$0 % 2 == 0}.first
/// 结果 0.0013990402221679688s
let first = nums.map{$0 + 1}.filter{$0 % 2 == 0}.first
/// 结果 0.04378199577331543s

可以看见,差异明显。