Just wanted to know which one would be faster?
AFAIK Set
uses hash
so it should be faster to find an element in Set. But in quite a few projects I've seen the usage of the array contains
where it could have used contains
on Set
.
Given a very quick test, set does look faster for .contains(
operations.
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")
This outputs:
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
On a mid-2015 macbook pro using swift 4.0.2. Longer arrays do impact the worst-case scenario. For an array of 24 strings (the same six strings above repeated four times), the array worst-case rose to 5.9s; others stayed broadly the same.
Note:
Array
to a Set
.Set
in stead of Array
.There are legitimate reasons a developer might use Array
even though Set
may be quicker for this one operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With