Created
November 9, 2021 06:16
-
-
Save PopFlamingo/6fc60870fa5b463a9daab82d08fe4db3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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