Swift 3 Array包含vs Set contains

时间:2017-09-24 01:37:28

标签: arrays swift algorithm set

只是想知道哪一个会更快?
AFAIK Set使用hash,因此在Set中查找元素应该更快。但是在很多项目中,我已经看到array containscontains上使用Set的用法。

1 个答案:

答案 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可能会更快地进行此操作。