How to avoid repeated heap allocation in SwiftUI?
Here we need to get our hands dirty by running and seeing the resualt of given sample codes.
As you can see here when we change the text value, the values of table view cells also get changed automatically which means that the subviews inside the body of a view also get updated ( get a new copy of it/ re-created).
Then, our Our @ObserableObject also will re-create , and there is a heap allocation for it as well.
You know heap allocation is expensive than stack allocation. So that we need to avoid these repeated heap allocations.
we can avoid repeated heap allocation by,
- Passing reference to subviews.
- Using @StateObject (SwiftUI 2.0 and above)
1️⃣. Passing reference to subviews.
Since the body get called when source of truth changed, we can hold the @ObservedObject in super view , so that it will not be destroyed when other source of truth changed.
https://gist.github.com/yodagamaheshan/6c18908e4eccab0c99d1c3c71ed95960.js
2️⃣. Using @StateObject
@StateObject is a combination of @State and @ObservedObject.
https://gist.github.com/yodagamaheshan/4c250d60799adeb0e6bc26ea9e62bb47.js