SwiftUI Series 13|SwiftUI performance optimization: writing methods that easily cause the page to become stuck
Many SwiftUI performance issues are caused by state granularity, calculation timing, and view update scope getting out of hand
When it comes to SwiftUI performance, two extreme judgments most often appear:
- “SwiftUI is inherently slow”
- “SwiftUI is absolutely fine, but I can’t write”
Both of these statements are too crude.
In real projects, many SwiftUI performance problems are indeed caused by these things getting out of control together:
- Status update granularity is too large
- View hierarchy is too deep
- Calculation is placed on the frequently refreshed path
- List and image link costs are too high
So what you really need to ask is:
Is a small change in the page causing recalculation and redrawing that is much larger than necessary?
1. The most common root cause of SwiftUI performance problems is that the update scope is too large
Many pages are stuck. On the surface, it seems that a certain component is heavy, but it is actually closer:
- A local state change
- but allows a large area of the interface to re-participate in calculations
This is especially important in declarative UIs. Because it says “recalculate the current description after the status changes”.
If state boundaries and component boundaries are not aligned, small changes will amplify into large-scale updates.
2. Putting high-cost calculations on the frequently refreshed path is one of the most common bad smells.
For example:
- Do complex formatting in
body - Do heavy data conversion during view construction
- Rebuild complex display models every time you refresh
These things are not visible when the amount of data is small. Once the page is refreshed frequently, the cost will be quickly amplified.
3. Lists and images almost always amplify SwiftUI’s performance issues
Because both scenarios will allow:
- Higher refresh rate
- More views
- The main thread is under greater pressure
If the state granularity is not fine enough, the page will easily drop frames.
4. Conclusion: The SwiftUI page becomes stuck, which is usually related to the loss of update granularity, calculation timing and view boundaries.
To put it in shorter form, I would say:
The most common root causes of SwiftUI performance problems are letting state changes affect the scope too much, allowing high-cost calculations to occur on high-frequency refresh paths, and not closing page boundaries.
Therefore, the truly effective optimization direction is usually to narrow the scope of influence, rather than doubting the entire framework from the beginning.
读完之后,下一步看什么
如果还想继续了解,可以从下面几个方向接着读。