Skip to content

Instantly share code, notes, and snippets.

@TellowKrinkle
Created June 9, 2017 21:20
Show Gist options
  • Save TellowKrinkle/77eaea4b1fae3a0d40fe9f84ca13288f to your computer and use it in GitHub Desktop.
Save TellowKrinkle/77eaea4b1fae3a0d40fe9f84ca13288f to your computer and use it in GitHub Desktop.
UInt64 vs String Access Times
import Foundation
func benchmark(_ function: () -> ()) -> Double {
let start = DispatchTime.now()
function()
let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start.uptimeNanoseconds) / 1_000_000_000
return elapsed
}
let count = 10_000_000
var intDic = [UInt64: UInt32]()
var stringIntDic = [UInt64: UInt32]()
var stringDic = [String: UInt32]()
print("Generating Ints")
let ints = (0..<count).map { _ in UInt64(arc4random()) << 32 | UInt64(arc4random()) }
print("Generating Strings")
let strings = ints.map(String.init)
print("Generating Output")
let randomOut = (0..<count).map { _ in arc4random() }
print("Benchmarking")
let intFill = benchmark {
for i in 0..<count {
intDic[ints[i]] = randomOut[i]
}
}
print("Int Fill: \(intFill)")
let stringIntFill = benchmark {
for i in 0..<count {
stringIntDic[UInt64(strings[i])!] = randomOut[i]
}
}
print("String -> Int Fill: \(stringIntFill)")
let stringFill = benchmark {
for i in 0..<count {
stringDic[strings[i]] = randomOut[i]
}
}
print("String Fill: \(stringFill)")
let intRead = benchmark {
for i in 0..<count {
_ = intDic[ints[i]]
}
}
print("Int Read: \(intRead)")
let stringIntRead = benchmark {
for i in 0..<count {
_ = stringIntDic[UInt64(strings[i])!]
}
}
print("String -> Int Read: \(stringIntRead)")
let stringRead = benchmark {
for i in 0..<count {
_ = stringDic[strings[i]]
}
}
print("String Read: \(stringRead)")
let intClear = benchmark {
for i in 0..<count {
intDic[ints[i]] = nil
}
}
print("Int Delete: \(intClear)")
let stringIntClear = benchmark {
for i in 0..<count {
stringIntDic[UInt64(strings[i])!] = nil
}
}
print("String -> Int Delete: \(stringIntClear)")
let stringClear = benchmark {
for i in 0..<count {
stringDic[strings[i]] = nil
}
}
print("String Delete: \(stringClear)")
import Foundation
let count = 10_000_000
let wait: UInt32 = 10_000_000
print("Generating Ints")
var ints = (0..<count).map { _ in UInt64(arc4random()) << 32 | UInt64(arc4random()) }
print("Done")
usleep(wait)
print("Generating Strings")
var strings = ints.map(String.init)
print("Done")
usleep(wait)
print("Deleting Ints")
ints = []
print("Done")
usleep(wait)
print("Deleting Strings")
strings = []
print("Done")
usleep(wait)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment