Skip to content

Instantly share code, notes, and snippets.

@PopFlamingo
Created November 9, 2021 06:16
Show Gist options
  • Save PopFlamingo/6fc60870fa5b463a9daab82d08fe4db3 to your computer and use it in GitHub Desktop.
Save PopFlamingo/6fc60870fa5b463a9daab82d08fe4db3 to your computer and use it in GitHub Desktop.
import Foundation
var sum = 0
for count in [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] {
print("Benchmarking for \(count) elements")
let randomKeys = Array(0..<count).shuffled()
let readKeysCount = count * 100
var randomReadKeys = [Int]()
for _ in 0..<readKeysCount {
randomReadKeys.append(randomKeys.randomElement()!)
}
let loopRuns = 100_000_000
let array = randomKeys.map({ ($0, Bool.random()) })
let dictionary = Dictionary<Int, Bool>(uniqueKeysWithValues: array)
var start = Date()
for i in 0..<loopRuns {
let key = randomReadKeys[i % readKeysCount]
let element = array.first(where: { $0.0 == key })!.1
sum &+= element ? 1 : 0
}
print("Array took \(Date().timeIntervalSince(start))")
start = Date()
for i in 0..<loopRuns {
let key = randomReadKeys[i % readKeysCount]
let element = dictionary[key]!
sum &+= element ? 1 : 0
}
print("Dictionary took \(Date().timeIntervalSince(start))")
print("\n===================\n")
}
print(sum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment