Lesson 6 of 9 · 24m
SwiftUI Performance and Lifecycle Under Pressure
Control view identity, expensive work, rendering frequency, and app lifecycle behavior so interfaces stay responsive on real devices.
Performance bugs in SwiftUI rarely announce themselves as one slow line. They appear as a list that hitches, a keyboard that stutters, or a detail screen that redraws because one unrelated counter changed. The first skill is not optimization. It is understanding identity, invalidation, and work.
Identity decides what survives
Stable identity preserves state; changing identity destroys and recreates views. Explicit .id() is useful and dangerous for the same reason:
DocumentEditor(document: document)
.id(document.id)This correctly resets the editor when another document is selected. It incorrectly discards drafts if the identifier is unstable or if you use an entire changing document as identity. Use the smallest stable identity that expresses the real lifetime.
Expensive work does not belong in body
body can be evaluated often. Treat it as a cheap description of state, not a work queue:
var body: some View {
List(filteredDocuments) { document in
DocumentRow(document: document)
}
}If filteredDocuments sorts a thousand rows and builds attributed strings every time, scrolling suffers. Compute transformations when inputs change, cache results intentionally, or move expensive pure work off the main actor.
Narrow observation reduces redraw scope
A large observable object can invalidate views that depend on unrelated properties. Split models by feature or expose narrower child models when profiling proves a problem. Measure with Instruments first; watch for long body evaluations and frequent updates.
Images, dates, and formatters are recurring offenders
Creating formatters is expensive. Cache them:
enum Formatters {
static let monthDay: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
}Large images need downsampling before display. LazyVStack defers view creation, not image decoding or network fetching triggered by rows that repeatedly appear and disappear.
Lifecycle is a state machine, not a hook collection
When the app backgrounds, tasks may suspend, sockets die, scene phases change, and unsaved drafts become your responsibility:
@Environment(\.scenePhase) private var scenePhase
RootView()
.onChange(of: scenePhase) { _, phase in
if phase == .background { draftStore.saveImmediately() }
}Do not rely on a graceful termination callback. iOS may terminate a suspended app without one. Durable state belongs in persistence before the user thinks something is saved.
Field notes
- Profile on a real device. Simulator performance and memory behavior are flattering lies.
taskis tied to view lifetime and cancels when the view disappears; do not use it for app-critical uploads.- Timers, sensors, and sockets can publish noisy updates. Batch them before invalidating UI.
- When a row flickers or loses state, inspect identity before increasing cache complexity.
Was this lesson helpful?