Skip to content

Instantly share code, notes, and snippets.

@mbrandonw
Last active March 7, 2023 09:30
Show Gist options
  • Save mbrandonw/188ee6afa8ccfb9ec20c024d63c4eba7 to your computer and use it in GitHub Desktop.
Save mbrandonw/188ee6afa8ccfb9ec20c024d63c4eba7 to your computer and use it in GitHub Desktop.
// See this Swift bug for more info: https://bugs.swift.org/browse/SR-9323
import Benchmark
struct User {
var name = "Blob"
var age = 42
}
@dynamicMemberLookup
struct UserWrapper {
var user: User
subscript<Value>(dynamicMember keyPath: WritableKeyPath<User, Value>) -> Value {
get { self.user[keyPath: keyPath] }
set { self.user[keyPath: keyPath] = newValue }
}
}
benchmark("Dynamic member lookup: setter only") {
(1...100_000).forEach { _ in
var user = UserWrapper(user: .init())
user.name = "Blob Jr."
user.age = 21
}
}
benchmark("Dynamic member lookup: getter and setter") {
(1...100_000).forEach { _ in
var user = UserWrapper(user: .init())
user.name = "Blob Jr."
user.age = 21
precondition(user.name == "Blob Jr.")
precondition(user.age == 21)
}
}
benchmark("Direct Access: setter only") {
(1...100_000).forEach { _ in
var user = UserWrapper(user: .init())
user.user.name = "Blob Jr."
user.user.age = 21
}
}
benchmark("Direct Access: getter and setter") {
(1...100_000).forEach { _ in
var user = UserWrapper(user: .init())
user.user.name = "Blob Jr."
user.user.age = 21
precondition(user.name == "Blob Jr.")
precondition(user.age == 21)
}
}
Benchmark.main()
/*
running Dynamic member lookup: setter only... done! (83.95 ms)
running Dynamic member lookup: getter and setter... done! (1355.41 ms)
running Direct Access: setter only... done! (76.52 ms)
running Direct Access: getter and setter... done! (73.11 ms)
name time std iterations
--------------------------------------------------------------------------
Dynamic member lookup: setter only 30.000 ns ± 232.94 % 1000000
Dynamic member lookup: getter and setter 987.000 ns ± 142.01 % 1000000
Direct Access: setter only 26.000 ns ± 1021.99 % 1000000
Direct Access: getter and setter 26.000 ns ± 916.78 % 1000000
Program ended with exit code: 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment