ios - Swift 数组和字典性能,removeAll() 与新实例

标签 ios swift

我有一个数组(或字典),需要清除它。性能方面,removeAll() 还是创建一个新实例更好?

var things = [Thing]()

// Need to clear things
things.removeAll()
// or
things = [Thing]()

最佳答案

(我不小心误读了你的问题并查找了DictionaryArray见下文)

字典

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))
}

如您所见,底层存储是唯一的属性,在初始化时分配。

全部删除

现在让我们看一下来自hereremoveAll() :

  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())
  }
}

与字典一样,_bufferArray 的唯一属性。

结论

Dictionary 相同:这两个语句在理论上几乎相同,但我可以想象在实践中可以优化初始化,因此它们完全相同.

关于ios - Swift 数组和字典性能,removeAll() 与新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112785/

相关文章:

ios - 如何以编程方式扩展/调出搜索栏?

iphone - 仅显示/使用 MFMailComposeViewController 中的 "To: "字段

ios - 使用 NSDateFormatter 快速格式化日期

ios - viewDidLoad 和 viewWillAppear 中的不同 subview 布局

swift - Swift 中的 PKCS#5 填充

ios - wkwebview 只显示白屏

ios - Swift 中 UITableView 中的重叠部分名称

ios PDFKit displaymode = singlepage 只显示pdf的第一页

ios - 如何在 Swift 中以编程方式旋转一组按钮?

ios - Swift 工具链是否消除了从未被调用的代码?