Skip to content

Instantly share code, notes, and snippets.

@tomquist
Last active April 3, 2019 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomquist/442fb5eb47311a4585f24b1a869cc344 to your computer and use it in GitHub Desktop.
Save tomquist/442fb5eb47311a4585f24b1a869cc344 to your computer and use it in GitHub Desktop.
Compare performance of iterating through a UTF8View of a 79 bytes String with iterating through its Data representation.
// Executed with optimization -Os on a MacBook Pro (15-inch, 2017) 2,8 GHz Intel Core i7
class StringPerformanceTest: XCTestCase {
// Takes in average 0.075 secs
func testPerformanceOfUTF8View() {
let data = "_cqeFf~cjVf@p@fA}AtAoB`ArAx@hA`GbIvDiFv@gAh@t@X\\|@z@`@Z\\Xf@Vf@VpA\\tATJ@NBBkC".data(using: .utf8)!
let string = String(decoding: data, as: UTF8.self)
measure {
for _ in 0...10_000 {
_ = string.utf8.reduce(into: 0, { count, _ in count += 1 })
}
}
}
// Takes in average 0.040 secs
func testPerformanceOfData() {
let data = "_cqeFf~cjVf@p@fA}AtAoB`ArAx@hA`GbIvDiFv@gAh@t@X\\|@z@`@Z\\Xf@Vf@VpA\\tATJ@NBBkC".data(using: .utf8)!
let string = String(decoding: data, as: UTF8.self)
measure {
for _ in 0...10_000 {
_ = string.data(using: .utf8)!.reduce(into: 0, { count, _ in count += 1 })
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment