只是想知道哪一个会更快?
AFAIK Set
使用hash
,因此在Set中查找元素应该更快。但是在很多项目中,我已经看到array contains
在contains
上使用Set
的用法。
答案 0 :(得分:2)
考虑到非常快速的测试,对于.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")
输出:
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
在使用swift 4.0.2的2015年中期macbook pro上。较长的阵列确实会影响最坏的情况。对于24个字符串的数组(重复四次以上相同的六个字符串),最坏情况下的数组上升到5.9s;其他人大致保持不变。
注意:
Array
投放到Set
的费用。Set
代替Array
时,您将失去排序并能够存储多个值的副本。开发人员使用Array
有正当理由,即使Set
可能会更快地进行此操作。