Array
中有一个filter
函数。我想知道它比使用像 for
这样的普通 loop
更便宜。
如果是,为什么?
最佳答案
现在 Swift 是开源的,很酷的一点是我们可以自己验证这一点。 Here's the current source code for Sequence.filter
(请注意,它已经使用了新名称 Sequence
和 Iterator
;SequenceType
和 GeneratorType
将在 Swift 3 中重命名):
/// Returns an `Array` containing the elements of `self`,
/// in order, that satisfy the predicate `includeElement`.
@warn_unused_result
public func filter(
@noescape includeElement: (Iterator.Element) throws -> Bool
) rethrows -> [Iterator.Element] {
var result = ContiguousArray<Iterator.Element>()
var iterator = self.makeIterator()
while let element = iterator.next() {
if try includeElement(element) {
result.append(element)
}
}
return Array(result)
}
它使用 while
循环而不是 for
循环,可能是因为该代码是在 for ... in
甚至是 a 之前编写的事情(虽然我还没有证实)。但你可以看到,它本质上是一个简单的循环,没有进行特殊优化。
关于arrays - Array.filter 比循环便宜吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36339138/