Skip to content

Commit c448e9d

Browse files
authored
Merge pull request #1 from cybozu/make-init-low-cost
イニシャライザを低コストにする
2 parents cf29032 + cf1f65e commit c448e9d

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# イニシャライザを低コストにする
2+
Viewのイニシャライザは何度も呼び出されるため、低コストに保ちます。
3+
4+
## Overview
5+
高コストなイニシャライザはよくあるパフォーマンス低下の原因です。
6+
7+
```swift
8+
struct DogRootView: View {
9+
@State private var model = FetchModel()
10+
11+
var body: some View {
12+
DogList(model.dogs)
13+
}
14+
}
15+
16+
@Observable class FetchModel {
17+
var dogs: [Dog]
18+
19+
init() {
20+
fetchDogs()
21+
}
22+
23+
func fetchDogs() {
24+
// Takes a long time
25+
}
26+
}
27+
```
28+
29+
この例では`DogRootView`のイニシャライザで`FetchModel`がイニシャライズされます。
30+
`FetchModel`のイニシャライザで処理に時間のかかる`fetchDogs`が同期的に呼び出されているため、`DogRootView`のイニシャライザが高コストとなっています。
31+
32+
### task modifierでイニシャライザのコストを下げる
33+
この場合は、`fetchDogs``async`にし、`.task`で非同期にデータを読み込むことでイニシャライザを低コストにします。
34+
35+
```swift
36+
struct DogRootView: View {
37+
@State private var model = FetchModel()
38+
39+
var body: some View {
40+
DogList(model.dogs)
41+
.task { await model.fetchDogs() }
42+
}
43+
}
44+
45+
@Observable class FetchModel {
46+
var dogs: [Dog]
47+
48+
init() { }
49+
50+
func fetchDogs() async {
51+
// Takes a long time
52+
}
53+
}
54+
```
55+
56+
> WWDC23 Demystify SwiftUI performance [12:20~](https://developer.apple.com/videos/play/wwdc2023/10160/?time=740)

Guide.docc/SwiftUIViewCodingGuidelines.md

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
- <doc:ChangeValueWhenSwitchingStyle>
4242
- <doc:HideViewWithOpacityWhenAvailable>
4343
- <doc:AssignUniqueValueToForEachID>
44+
- <doc:MakeInitializerLowCost>
4445

4546
### The Art of API Design
4647
- <doc:ProvidesContainerViewAccessViaProxy>

0 commit comments

Comments
 (0)