guide-swiftui-performance-audit
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGuide Skill — This is an expert workflow/pattern guide, not API reference documentation. Originally from Dimillian/Skills by Thomas Ricouard. MIT License.
指南技能 — 这是一份专家级工作流/模式指南,而非API参考文档。 最初源自Thomas Ricouard的Dimillian/Skills,采用MIT许可证。
SwiftUI Performance Audit
SwiftUI性能审计
Overview
概述
Audit SwiftUI view performance end-to-end, from instrumentation and baselining to root-cause analysis and concrete remediation steps.
端到端审计SwiftUI视图性能,覆盖从性能检测、基准测试到根因分析和具体修复步骤的全流程。
Workflow Decision Tree
工作流决策树
- If the user provides code, start with "Code-First Review."
- If the user only describes symptoms, ask for minimal code/context, then do "Code-First Review."
- If code review is inconclusive, go to "Guide the User to Profile" and ask for a trace or screenshots.
- 如果用户提供了代码,从「代码优先审查」开始。
- 如果用户仅描述了问题症状,先索要最小可复现代码/上下文,再进行「代码优先审查」。
- 如果代码审查无法得出结论,进入「指导用户做性能分析」步骤,索要追踪数据或截图。
1. Code-First Review
1. 代码优先审查
Collect:
- Target view/feature code.
- Data flow: state, environment, observable models.
- Symptoms and reproduction steps.
Focus on:
- View invalidation storms from broad state changes.
- Unstable identity in lists (churn,
idper render).UUID() - Top-level conditional view swapping (returning different root branches).
if/else - Heavy work in (formatting, sorting, image decoding).
body - Layout thrash (deep stacks, , preference chains).
GeometryReader - Large images without downsampling or resizing.
- Over-animated hierarchies (implicit animations on large trees).
Provide:
- Likely root causes with code references.
- Suggested fixes and refactors.
- If needed, a minimal repro or instrumentation suggestion.
收集信息:
- 目标视图/功能代码。
- 数据流:状态、环境、可观测模型。
- 问题症状和复现步骤。
重点排查:
- 大范围状态变更引发的视图失效风暴。
- 列表中的不稳定标识(频繁变更、每次渲染都生成
id)。UUID() - 顶层条件视图切换(返回完全不同的根分支)。
if/else - 中的 heavy 操作(格式化、排序、图片解码)。
body - 布局抖动(深层栈、、偏好链)。
GeometryReader - 未做下采样或调整尺寸的大图。
- 过度动画的视图层级(大型视图树上的隐式动画)。
输出内容:
- 关联代码引用的潜在根因。
- 修复和重构建议。
- 必要时提供最小复现示例或性能检测建议。
2. Guide the User to Profile
2. 指导用户做性能分析
Explain how to collect data with Instruments:
- Use the SwiftUI template in Instruments (Release build).
- Reproduce the exact interaction (scroll, navigation, animation).
- Capture SwiftUI timeline and Time Profiler.
- Export or screenshot the relevant lanes and the call tree.
Ask for:
- Trace export or screenshots of SwiftUI lanes + Time Profiler call tree.
- Device/OS/build configuration.
讲解如何使用Instruments收集数据:
- 使用Instruments中的SwiftUI模板(Release构建包)。
- 复现 exact 交互操作(滚动、导航、动画)。
- 捕获SwiftUI时间线和时间分析器数据。
- 导出或截取相关轨道和调用栈的截图。
索要信息:
- 导出的追踪文件,或SwiftUI轨道+时间分析器调用栈的截图。
- 设备/操作系统/构建配置信息。
3. Analyze and Diagnose
3. 分析与诊断
Prioritize likely SwiftUI culprits:
- View invalidation storms from broad state changes.
- Unstable identity in lists (churn,
idper render).UUID() - Top-level conditional view swapping (returning different root branches).
if/else - Heavy work in (formatting, sorting, image decoding).
body - Layout thrash (deep stacks, , preference chains).
GeometryReader - Large images without downsampling or resizing.
- Over-animated hierarchies (implicit animations on large trees).
Summarize findings with evidence from traces/logs.
优先排查常见的SwiftUI问题诱因:
- 大范围状态变更引发的视图失效风暴。
- 列表中的不稳定标识(频繁变更、每次渲染都生成
id)。UUID() - 顶层条件视图切换(返回完全不同的根分支)。
if/else - 中的 heavy 操作(格式化、排序、图片解码)。
body - 布局抖动(深层栈、、偏好链)。
GeometryReader - 未做下采样或调整尺寸的大图。
- 过度动画的视图层级(大型视图树上的隐式动画)。
结合追踪数据/日志中的证据总结排查结果。
4. Remediate
4. 问题修复
Apply targeted fixes:
- Narrow state scope (/
@Statecloser to leaf views).@Observable - Stabilize identities for and lists.
ForEach - Move heavy work out of (precompute, cache,
body).@State - Use or value wrappers for expensive subtrees.
equatable() - Downsample images before rendering.
- Reduce layout complexity or use fixed sizing where possible.
采用针对性的修复方案:
- 缩小状态作用范围(将/
@State放到更靠近叶子视图的位置)。@Observable - 稳定和列表的标识。
ForEach - 将heavy操作移出(预计算、缓存、存入
body)。@State - 对高开销子树使用或值包装器。
equatable() - 渲染前对图片做下采样。
- 降低布局复杂度,尽可能使用固定尺寸。
Common Code Smells (and Fixes)
常见代码坏味道(及修复方案)
Look for these patterns during code review.
代码审查过程中重点排查以下模式。
Expensive formatters in body
bodybody
中使用高开销的格式化器
bodyswift
var body: some View {
let number = NumberFormatter() // slow allocation
let measure = MeasurementFormatter() // slow allocation
Text(measure.string(from: .init(value: meters, unit: .meters)))
}Prefer cached formatters in a model or a dedicated helper:
swift
final class DistanceFormatter {
static let shared = DistanceFormatter()
let number = NumberFormatter()
let measure = MeasurementFormatter()
}swift
var body: some View {
let number = NumberFormatter() // 分配内存慢
let measure = MeasurementFormatter() // 分配内存慢
Text(measure.string(from: .init(value: meters, unit: .meters)))
}建议在模型或专用工具类中使用缓存的格式化器:
swift
final class DistanceFormatter {
static let shared = DistanceFormatter()
let number = NumberFormatter()
let measure = MeasurementFormatter()
}Computed properties that do heavy work
执行heavy操作的计算属性
swift
var filtered: [Item] {
items.filter { $0.isEnabled } // runs on every body eval
}Prefer precompute or cache on change:
swift
@State private var filtered: [Item] = []
// update filtered when inputs changeswift
var filtered: [Item] {
items.filter { $0.isEnabled } // 每次body求值都会运行
}建议预计算或在变更时缓存结果:
swift
@State private var filtered: [Item] = []
// 输入变更时更新filteredSorting/filtering in body
or ForEach
bodyForEach在body
或ForEach
中做排序/过滤
bodyForEachswift
List {
ForEach(items.sorted(by: sortRule)) { item in
Row(item)
}
}Prefer sort once before view updates:
swift
let sortedItems = items.sorted(by: sortRule)swift
List {
ForEach(items.sorted(by: sortRule)) { item in
Row(item)
}
}建议在视图更新前完成一次排序:
swift
let sortedItems = items.sorted(by: sortRule)Inline filtering in ForEach
ForEach在ForEach
中做内联过滤
ForEachswift
ForEach(items.filter { $0.isEnabled }) { item in
Row(item)
}Prefer a prefiltered collection with stable identity.
swift
ForEach(items.filter { $0.isEnabled }) { item in
Row(item)
}建议使用带有稳定标识的预过滤集合。
Unstable identity
不稳定标识
swift
ForEach(items, id: \.self) { item in
Row(item)
}Avoid for non-stable values; use a stable ID.
id: \.selfswift
ForEach(items, id: \.self) { item in
Row(item)
}避免对非稳定值使用,请使用稳定ID。
id: \.selfTop-level conditional view swapping
顶层条件视图切换
swift
var content: some View {
if isEditing {
editingView
} else {
readOnlyView
}
}Prefer one stable base view and localize conditions to sections/modifiers (for example inside , row content, , or ). This reduces root identity churn and helps SwiftUI diffing stay efficient.
toolbaroverlaydisabledswift
var content: some View {
if isEditing {
editingView
} else {
readOnlyView
}
}建议使用单一稳定的基础视图,将条件限定在局部的区块/修饰符中(例如放在、行内容、或内部)。这可以减少根标识的频繁变更,帮助SwiftUI更高效地做差异对比。
toolbaroverlaydisabledImage decoding on the main thread
主线程上的图片解码
swift
Image(uiImage: UIImage(data: data)!)Prefer decode/downsample off the main thread and store the result.
swift
Image(uiImage: UIImage(data: data)!)建议在非主线程完成解码/下采样后再存储结果。
Broad dependencies in observable models
可观测模型中的依赖范围过宽
swift
@Observable class Model {
var items: [Item] = []
}
var body: some View {
Row(isFavorite: model.items.contains(item))
}Prefer granular view models or per-item state to reduce update fan-out.
swift
@Observable class Model {
var items: [Item] = []
}
var body: some View {
Row(isFavorite: model.items.contains(item))
}建议使用细粒度的视图模型或单条目状态,减少更新的扩散范围。
5. Verify
5. 效果验证
Ask the user to re-run the same capture and compare with baseline metrics.
Summarize the delta (CPU, frame drops, memory peak) if provided.
要求用户重新运行相同的采集流程,和基准指标做对比。如果用户提供了数据,总结优化前后的差值(CPU、丢帧、内存峰值)。
Outputs
输出内容
Provide:
- A short metrics table (before/after if available).
- Top issues (ordered by impact).
- Proposed fixes with estimated effort.
提供以下信息:
- 简短的指标对比表(如果有优化前后数据)。
- top问题列表(按影响大小排序)。
- 建议的修复方案和预估工作量。
References
参考资料
Add Apple documentation and WWDC resources under as they are supplied by the user.
references/- Optimizing SwiftUI performance with Instruments:
references/optimizing-swiftui-performance-instruments.md - Understanding and improving SwiftUI performance:
references/understanding-improving-swiftui-performance.md - Understanding hangs in your app:
references/understanding-hangs-in-your-app.md - Demystify SwiftUI performance (WWDC23):
references/demystify-swiftui-performance-wwdc23.md
用户提供的Apple官方文档和WWDC资源请放在目录下:
references/- 使用Instruments优化SwiftUI性能:
references/optimizing-swiftui-performance-instruments.md - 理解并提升SwiftUI性能:
references/understanding-improving-swiftui-performance.md - 理解应用中的卡顿问题:
references/understanding-hangs-in-your-app.md - 揭秘SwiftUI性能(WWDC23):
references/demystify-swiftui-performance-wwdc23.md