LoginSignup
1
1

More than 3 years have passed since last update.

SwiftのKeyPathは結構遅いから気を付けろ

Posted at

実験

SwiftのKeyPathは普通のプロパティアクセスの100倍遅い。

両方を100万回実行して確認。

var a: Int = 0
class Person {
    var name: String { didSet { a += 1 } }
    init(name: String) { self.name = name }
}

// ドットアクセス
let bobName = "Bob"
let bob = Person(name: bobName)
let start1 = Date()
for _ in 0..<1000000 {
    bob.name = bobName
}
print(Date().timeIntervalSince(start1), "s")

// KeyPathアクセス
let start2 = Date()
let nameKeyPath = \Person.name
for _ in 0..<1000000 {
    bob[keyPath: nameKeyPath] = bobName
}
print(Date().timeIntervalSince(start2), "s")

print(a) // 20000

結果

普通のアクセス KeyPath
0.0066s 0.6208s

KeyPathあまり使わないようにしよう...

PlayGroundでは何故か逆になります。
多分Debug表示の関係でプロパティアクセスに特殊な処理がされてる。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1