Skip to content

Instantly share code, notes, and snippets.

@danieltmbr
Last active September 29, 2017 10:06
Show Gist options
  • Save danieltmbr/66b78da6a34f2400946a5f8191b1ef63 to your computer and use it in GitHub Desktop.
Save danieltmbr/66b78da6a34f2400946a5f8191b1ef63 to your computer and use it in GitHub Desktop.
Swift integer & byte array to ascii string convert performance test
func measure(closure: (()->Void)) {
let start = Date()
closure()
let interval = Date().timeIntervalSince(start)
print(interval)
}
extension Int {
var ascii: [UInt8] {
var array: [UInt8] = []
var num = self
repeat {
array.append(UInt8(num%10 + 0x30))
num = num/10
} while num > 0
return array.reversed()
}
var ascii2: [UInt8] {
var array: [UInt8] = []
var num = self
repeat {
array.insert(UInt8(num%10 + 0x30), at: 0)
num = num/10
} while num > 0
return array
}
}
measure {
for _ in 0..<100 {
let num = 123456789
let asc = num.ascii
}
}
measure {
for _ in 0..<100 {
let num = 123456789
let asc = num.ascii2
}
}
measure {
for _ in 0..<100 {
let num = 123456789
let asc = "\(num)".data(using: .ascii)
}
}
extension String {
var ascii: [UInt8] {
return unicodeScalars.map { return UInt8($0.value) }
}
var ascii2: [UInt8] {
return [UInt8](self.data(using: .ascii)!)
}
}
measure {
for _ in 0..<2000 {
let str = "asdfg 123 - qwe"
let asci = str.ascii
}
}
measure {
for _ in 0..<2000 {
let str = "asdfg 123 - qwe"
let asci = str.ascii2
}
}
let str = "asdfg 123 - qwe"
print(str.ascii == str.ascii2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment