In SwiftUI, why is building a formatter or sorting and filtering a large array inside body a performance problem, and where should that work go?
answer
- body is not a one-time setup
- runs on every dependency change
- main actor, same thread as scrolling
- format styles and stored derived data
basics
~20 sSwiftUI can re-run a view's body many times, on the main actor, whenever something it depends on changes, so work inside body repeats on every update. Use format styles, and compute sorted or filtered data once, when its inputs change.
solid answer
~40 sA view's `body` is a description SwiftUI re-reads whenever a dependency changes: an observable property it read, its own `@State`, or a new value from its parent. `View` is main-actor isolated, so everything in `body` runs on the main thread. Building a `NumberFormatter` or sorting and filtering thousands of items there repeats that cost on every evaluation, which shows up as long body updates and scroll hitches. I move formatting to `Text(value, format: .currency(code:))`, store derived arrays in the model and refresh them when the source or filter changes, and push heavy async work into `.task`. A computed property on the model doesn't help, because it recomputes on every read.
code
swift · 29 linesimport SwiftUI
struct Trade: Identifiable {
let id: Int
let symbol: String
let amount: Double
}
@Observable @MainActor final class TradesModel {
var trades: [Trade] = [] { didSet { refresh() } }
var prefix = "" { didSet { refresh() } }
private(set) var visible: [Trade] = []
private func refresh() {
visible = trades
.filter { prefix.isEmpty || $0.symbol.hasPrefix(prefix) }
.sorted { $0.amount > $1.amount }
}
}
struct TradesView: View {
let model: TradesModel
var body: some View {
List(model.visible) { trade in
Text(trade.amount, format: .currency(code: "USD"))
}
}
}go deeper
Recall that body can run many times and runs on the main actor. Name format styles for formatting and storing derived data for sorting and filtering.
Explain what makes body re-run: a read observable property, the view's own state, or a new value from the parent. Show why a computed property does not cache.
Tie the cost to user-visible hitches and long body updates, and show where each kind of work moves: format styles, stored derived arrays, and async work in task.
Turn this into a review rule that body reads and composes but never computes data, while leaving cheap presentation logic alone so the rule does not breed needless indirection.
## What body is for A SwiftUI **view** is a lightweight struct, and its `body` is a description of what should be on screen right now. SwiftUI reads that description whenever it needs a fresh one, so `body` is not a one-time setup method like a view controller's `viewDidLoad`. The `View` protocol is isolated to the **main actor** (Apple's documentation: a conforming type "inherits `@preconcurrency @MainActor` isolation"), which means every line inside `body` runs on the main thread, the same thread that handles touches and scrolling. ## Why work in body repeats SwiftUI evaluates a view's `body` again when something that body depends on changes: - an observable property the body **read** changed (with `@Observable`, only the properties actually read count); - the view's own `@State` changed; - the parent re-ran and handed the view a new value that SwiftUI did not consider equal to the old one. On a busy screen, such as a trading list fed by live prices, that can be many evaluations per second. Anything expensive written inside `body` is paid on **every one** of them, on the main thread. When a single evaluation takes too long, Instruments can flag it as a long view body update, and the user feels it as a hitch while scrolling or a frozen tap. ## The usual offenders | Work inside body | Why it hurts | Where it goes | |---|---|---| | `NumberFormatter()` or `DateFormatter()` built and configured | object allocation and setup on every run | a format style, `Text(value, format: …)`, or one shared formatter | | `array.sorted(…)` / `filter(…)` over thousands of items | work that grows with the data, repeated even when the data did not change | a stored, derived array updated when its inputs change | | decoding JSON, resizing images, reading files | slow and often blocking | an async task started from `.task`, off the main actor | | building large dictionaries or lookups | repeated allocation | the model, built once | ## Where each piece of work moves 1. **Formatting.** Use a `FormatStyle` inline: `Text(trade.amount, format: .currency(code: "USD"))`. A format style is a small value that describes the formatting, so your code no longer allocates and configures a formatter object on each run. If you need an old-style `Formatter`, create it once (a `static let`) rather than inside `body`. 2. **Sorting and filtering.** Compute the result **when its inputs change**, not when it is displayed. In an `@Observable` model, keep the source array and the filter text as stored properties and refresh a stored `visible` array from their `didSet`. The view then only reads `model.visible`. 3. **Heavy or asynchronous work.** Start it from `.task` (covered with view lifecycle and async work) and keep it off the main actor; write the result back to state when it finishes. A trap worth naming: moving the filter into a **computed property** on the model does not make it cheaper. A computed property runs every time it is read, so each body evaluation still filters and sorts. Apple's documentation notes that Observation can track a computed property through the stored properties it uses, which keeps the view correct, but it does not cache the result. Caching is something you do yourself by storing it. ```swift @Observable @MainActor final class TradesModel { var trades: [Trade] = [] { didSet { refresh() } } var prefix = "" { didSet { refresh() } } private(set) var visible: [Trade] = [] private func refresh() { visible = trades .filter { prefix.isEmpty || $0.symbol.hasPrefix(prefix) } .sorted { $0.amount > $1.amount } } } ``` ## Checking the fix - Put `let _ = Self._printChanges()` in the view's body during debugging to see **why** it re-runs; the expensive work was being repeated each of those times. - Profile a Release build on a real device with the SwiftUI template in Instruments to see **how long** each body evaluation takes before and after. - Keep the rule simple for a code review: `body` reads data and composes views; it does not compute the data. None of this means `body` must be empty of logic. A ternary that picks a colour, a short `if` that chooses a subview or a string interpolation is fine. The concern is work whose cost grows with the data or that allocates heavy objects, repeated on every update.
- Why doesn't a computed property on the @Observable model fix the cost?A computed property runs on every access, so each body evaluation that reads it still filters and sorts. Observation keeps the view correct by tracking the stored properties the computed one uses, but it does not cache the result. Store the derived array and update it when its inputs change.
- Is any logic in body acceptable?Yes. Choosing a colour with a ternary, an `if` that picks a subview or a short string interpolation are cheap and belong in `body`. The rule targets work whose cost grows with the data, or that allocates heavy objects, because it is repeated on every update.
- body runs once when the view appears, like viewDidLoad
- SwiftUI caches body, so expensive work there is paid only once
- a computed property on the model caches the sorted result
- SwiftUI moves body work to a background thread automatically