skip to content

Redraw Cost and Diagnosis

Slow SwiftUI screens usually re-run too many bodies; narrowing dependencies, splitting views and lazy containers fix that. Interviewers ask how you find which view redraws and why.

on this pageshow

explore

questions

6

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?

level: juniorimportance: must knowfreq 65%

answer

  1. body is not a one-time setup
  2. runs on every dependency change
  3. main actor, same thread as scrolling
  4. format styles and stored derived data

basics

~20 s

SwiftUI 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 s

A 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 lines
swift
import 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

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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
open as a page

In a SwiftUI stocks dashboard backed by one ObservableObject, a price tick every second re-runs the header, the chart and all 500 rows; why, and how do you narrow it?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Any @Published change fires objectWillChange, and every view observing that ObservableObject re-runs, read or not. Move to @Observable (iOS 17) with one object per symbol, mutate prices in place, and read each price only in its row.

open as a page

In SwiftUI, what does calling Self._printChanges() inside a view's body report, and how do you read lines such as '@self changed' or '\Quote.price changed'?

level: middleimportance: should knowfreq 55%

basics

~20 s

Self._printChanges() prints, each time a view's body runs, what SwiftUI saw change: @self for a new value from the parent, @identity for a freshly created view, a state storage name, or an observed key path. It is an undocumented debug aid.

open as a page

In SwiftUI, why does extracting part of a body into its own View struct narrow redraws when a computed property returning some View does not?

level: middleimportance: should knowfreq 58%

basics

~20 s

SwiftUI tracks dependencies per view body. A computed property runs inside the parent's body, so its reads make the parent re-run; a separate View struct has its own body, so only it re-runs when what it reads changes.

open as a page

In a SwiftUI watchlist, each row conforms to Equatable comparing only its ticker symbol and is wrapped with .equatable(); what can go wrong, and when is that worth doing?

level: seniorimportance: should knowfreq 38%

basics

~20 s

With .equatable(), the row's == decides whether a new value from the parent counts as changed. Comparing only the symbol lets a new price or a new action closure be treated as unchanged, so the row can show stale data or run stale actions.

open as a page

As the lead of a SwiftUI app with several slow screens, which redraw rules would you enforce in code review, and when would you profile instead of guessing?

level: principalimportance: should knowfreq 42%

basics

~20 s

Enforce a few mechanism-based defaults: no computation in body, volatile values read where displayed, @Observable models, real view splits, and justified .equatable(). Profile on a real device with the SwiftUI instrument whenever users report hitches or a change claims a speed-up.

open as a page