Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Created July 27, 2021 00:11
Show Gist options
  • Save nicklockwood/f44da6e8896f264dfdc2aa25d7c6b8c4 to your computer and use it in GitHub Desktop.
Save nicklockwood/f44da6e8896f264dfdc2aa25d7c6b8c4 to your computer and use it in GitHub Desktop.
A quick test to compare performance of different dictionary lookups in Swift
// A quick test to compare performance of different dictionary lookups in Swift.
// Note: Results recorded on a 2020 M1 MBP. be sure to run with "Optimize for Speed [-O]
import Foundation
let iterations = 1000000
var dictionary = [Int: Int]()
for i in 0 ..< iterations {
dictionary[i] = Int.random(in: 0 ..< 1000)
}
let start = CFAbsoluteTimeGetCurrent()
for i in 0 ..< iterations {
if !dictionary.keys.contains(i) {
print("uh...?")
}
}
let mid = CFAbsoluteTimeGetCurrent()
for i in 0 ..< iterations {
if dictionary[i] == nil {
print("uh...?")
}
}
let end = CFAbsoluteTimeGetCurrent()
print("keys.contains", mid - start) // 0.02835094928741455
print("subscript", end - mid) // 0.038653016090393066
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment