Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 Array contains vs Set contains

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.

like image 200
MANN Avatar asked Jan 30 '23 13:01

MANN


1 Answers

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:

  • This test does not take into account the cost of casting an Array to a Set.
  • I had to bump it up to one million iterations to get a value over a second.
  • You lose ordering and the ability to store multiple copies of a value when using Set in stead of Array.

There are legitimate reasons a developer might use Array even though Set may be quicker for this one operation.

like image 69
ReactiveRaven Avatar answered Feb 05 '23 20:02

ReactiveRaven