Created
July 27, 2021 00:11
-
-
Save nicklockwood/f44da6e8896f264dfdc2aa25d7c6b8c4 to your computer and use it in GitHub Desktop.
A quick test to compare performance of different dictionary lookups in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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