我有一个数组(或字典),需要清除它。性能方面,removeAll()
还是创建一个新实例更好?
var things = [Thing]()
// Need to clear things
things.removeAll()
// or
things = [Thing]()
最佳答案
(我不小心误读了你的问题并查找了Dictionary
,Array
见下文)
字典
thing = [String : Thing]()
与 thing.removeAll()
现在 Swift 是开源的,我们可以看看这两个语句是否真的做了一些不同的事情。
新的初始化
在深入研究源代码后,我找到了Dictionary
的初始化程序 here :
public init() {
self = Dictionary<Key, Value>(minimumCapacity: 0)
}
/// Create a dictionary with at least the given number of
/// elements worth of storage. The actual capacity will be the
/// smallest power of 2 that's >= `minimumCapacity`.
public init(minimumCapacity: Int) {
_variantStorage =
.Native(_NativeStorage.Owner(minimumCapacity: minimumCapacity))
}
如您所见,底层存储是唯一的属性,在初始化时分配。
全部删除
现在让我们看一下来自here 的removeAll()
:
internal mutating func removeAll(keepCapacity keepCapacity: Bool) {
if count == 0 {
return
}
if !keepCapacity {
self = .Native(NativeStorage.Owner(minimumCapacity: 2))
return
}
if _fastPath(guaranteedNative) {
nativeRemoveAll()
return
}
switch self {
case .Native:
nativeRemoveAll()
case .Cocoa(let cocoaStorage):
#if _runtime(_ObjC)
self = .Native(NativeStorage.Owner(minimumCapacity: cocoaStorage.count))
#else
_sanityCheckFailure("internal error: unexpected cocoa ${Self}")
#endif
}
}
在这里您可以看到条件 !keepCapacity
将为真,因为 removeAll()
只是 removeAll(keepCapacity:)
false
的默认参数。此代码来自存储枚举,因此它用最小容量为 2 的新空存储替换自身。
结论
这两个语句在理论上几乎相同,但我可以想象在实践中可以优化初始化,以便它们完全相同。
数组
things = [Thing]()
与 things.removeAll()
新的初始化
对于数组,更容易看到 here :
public init() {
_buffer = _Buffer()
}
全部删除
参见 here :
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
if !keepCapacity {
_buffer = _Buffer()
}
else {
self.replaceRange(self.indices, with: EmptyCollection())
}
}
与字典一样,_buffer
是Array
的唯一属性。
结论
与 Dictionary
相同:这两个语句在理论上几乎相同,但我可以想象在实践中可以优化初始化,因此它们完全相同.
关于ios - Swift 数组和字典性能,removeAll() 与新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112785/