Swift 3 Array 包含 vs Set 包含

MAN*_*ANN 4 arrays algorithm set swift

只是想知道哪个会更快?
AFAIKSet使用,hash因此在 Set 中查找元素应该更快。但是在相当多的项目中,我已经看到了array contains它可以containsSet.

Rea*_*ven 8

给定一个非常快速的测试,set 的操作看起来确实更快.contains(

import Foundation

let iterations = 1000000
let array = [ "cat", "dog", "fish", "gerbil", "hamster", "octopus" ]
let set = Set(array)
let bestCase = "cat"
let worstCase = "apple" // Note: Not in the collection.

print("For \(iterations) iterations:")

var start = Date()
for _ in 1...iterations {
    _ = array.contains(worstCase)
}
print("Array took \(-start.timeIntervalSinceNow)s in the worst case")

start = Date()
for _ in 1...iterations {
    _ = set.contains(worstCase) // Note: Not in the collection.
}
print("Set   took \(-start.timeIntervalSinceNow)s in the worst case")

start = Date()
for _ in 1...iterations {
    _ = array.contains(bestCase)
}
print("Array took \(-start.timeIntervalSinceNow)s in the best case")

start = Date()
for _ in 1...iterations {
    _ = set.contains(bestCase)
}

print("Set   took \(-start.timeIntervalSinceNow)s in the best case")
Run Code Online (Sandbox Code Playgroud)

这输出:

For 1000000 iterations:
Array took 1.67272698879242s in the worst case
Set   took 0.307300984859467s in the worst case
Array took 0.412128031253815s in the best case
Set   took 0.216085016727448s in the best case
Run Code Online (Sandbox Code Playgroud)

在 2015 年年中使用 swift 4.0.2 的 macbook pro 上。更长的阵列确实会影响最坏的情况。对于 24 个字符串的数组(上面相同的 6 个字符串重复了四次),数组最坏情况上升到 5.9s;其他人大致保持不变。

笔记:

  • 此测试未考虑将 an 转换Array为 a的成本Set
  • 我不得不将它提高到一百万次迭代才能在一秒内获得一个值。
  • 你失去了订货和使用时存储的值的多个副本的能力Set在代替Array

开发人员可能会使用合法的理由,Array即使Set这一项操作可能更快。