---
name: ios-macos-speedup
description: Make a slow or janky interaction in an iOS or macOS app smooth - switching tabs, accounts or screens, opening an item, an animation that stutters, jumps or cannot be interrupted. Gives a measure-first method (a main-thread stall log per user action, scripted input, a sampling profile for attribution, filmed frames) and the fixes that generalise - keep views alive instead of rebuilding them, reuse views and web views outside scrolling lists too, lay out repeated views by hand with frames and cache that layout, stop fighting framework animation threads, strip per-frame work, redirect animations mid-flight, move only data work off the main thread. Use whenever an app's UI feels slow, laggy or frozen, drops frames, or when asked to profile UI, reach 60 or 120 fps, or offload work from the main thread, even if the word performance never comes up.
---

# Speeding up iOS and macOS apps

How to make one interaction in an Apple-platform app stop dropping frames.

## The stance

- **One interaction, measured per action, before and after.** "Worst stall 558 ms, 40 frames
  dropped per switch" tells you whether a change mattered. A feeling does not, and a profile alone
  does not either.
- **Remove work before relocating it.** In order of leverage: do not do it, do it once instead of
  N times, do it off the main thread, do it later. The large wins are usually work that never
  needed to happen. A background thread is the third resort, not the first.
- **Verify the way the user uses it:** at their speed, with their amount of data, in every
  direction. A fix checked in one configuration is not checked.

## Measure

**Budget.** A frame is 16.7 ms at 60 Hz and 8.3 ms at 120 Hz. One pass of the main run loop that
runs longer drops `floor(stall / frame)` frames.

**Scenarios.** Name the action and the states it runs between. Order the states from lightest to
heaviest and measure each: the lightest isolates the cost of the action itself, the heaviest shows
what content adds. Run each *slow* (every action settles) and *fast* (actions closer together than
the animation lasts). Fast runs expose queued work and animations that cannot be interrupted.

**Build.** Optimised, attachable, with realistic data. Debug builds overstate some costs several
times over and point the work in the wrong direction.

**Stall log.** Time every pass of the main run loop and log the long ones. It costs two clock reads
per pass, so unlike a profiler it does not distort what it measures:

```swift
/// Call once at launch. Logs each main run-loop pass longer than `threshold` seconds.
func installStallLog(threshold: CFTimeInterval = 0.008) {
    var wokeAt: CFTimeInterval?
    let observer = CFRunLoopObserverCreateWithHandler(
        nil, CFRunLoopActivity.afterWaiting.rawValue | CFRunLoopActivity.beforeWaiting.rawValue,
        true, CFIndex.max            // last, so the Core Animation commit is inside the timed pass
    ) { _, activity in
        let now = CACurrentMediaTime()
        if activity == .afterWaiting {
            wokeAt = now
        } else if let start = wokeAt {
            wokeAt = nil
            if now - start >= threshold {
                fputs(String(format: "STALL start=%.4f ms=%.1f\n", start, (now - start) * 1000), stderr)
            }
        }
    }
    CFRunLoopAddObserver(CFRunLoopGetMain(), observer, .commonModes)
}
```

A pass covers the event, everything it triggered, and the layout, drawing and commit at its end. It
does not see the render server, the GPU or other threads.

**Scripted input on the same clock.** Drive the action from a script that logs each press with
`CACurrentMediaTime()`, which every process on the machine shares, and join the two logs. A person
cannot press twice 60 ms apart, or say when they pressed. On the Mac, post events to the app's pid
rather than to "the frontmost app": with two copies of an app running, anything addressed by name
reaches the wrong one sooner or later. On iOS, use a UI test.

**The numbers, per action:** worst stall, frames dropped, total main-thread time, and when the UI
settled. Take them with no profiler attached; a sampler stretches stalls two to three times.

**Attribution.** Now attach a sampler and read it for shares, not durations. Read three things:

- *Your code:* which functions own the time (view construction, reloads, cell configuration, state
  sends, observers).
- *The commit:* how much is layout, how much is drawing, how much is window bookkeeping. This is
  often half the stall, and it is the bill for what your code changed.
- *Waits:* the main thread blocked on a lock, or on the render server inside a commit. Idle-time
  filters hide these, and they are where the 100 to 300 ms outliers come from. Find the thread that
  holds what the main thread wants.

Frameworks also log their own expensive steps; read the process's system log.

**Film.** Record the screen and step through consecutive frames. Stall numbers cannot show a blank
frame, stale content flashing, an animation that starts a frame late, or a jump. Count the frames
that changed during each leg of an animation: one changed frame where a slide should be is a jump.

## Fix, in order of leverage

### 1. Do not rebuild what you will show again

*Sign:* switching between contexts of the same shape (accounts, tabs, documents, chats) builds
views, reloads lists and lays out fresh hierarchies, and the way back costs the same again. Usually
one set of views is re-pointed at whichever context is selected.

*Move:* give each context its own view subtree and keep it. A switch hides one and shows another.
Keep the most recent few and drop the rest, along with the subtrees of contexts that are gone.

What makes it work:

- **Hide; do not remove.** A hidden view is not redrawn when shown again. A view taken out of its
  window and put back is. (Checked on AppKit.)
- **Pin each subtree to its own context,** for what it reads and for where its actions go. Derive
  shared chrome (toolbar, title) from the selected context's state, not from "the current subtree".
- **A hidden subtree is still alive.** Decide what its alerts, timers, shortcuts, first responder
  and appear-time work should do while it is hidden. On AppKit, hiding and showing a view sends
  disappear and appear to its controllers and hidden views get no key equivalents; do not assume
  UIKit behaves the same.
- **Bound the memory.** Each kept subtree holds its views, and each web view in it holds a process.

For scale: 50 to 560 ms of blocked main thread per switch became about 10 ms, every context kept its
scroll position, and the chain of "reload, refetch, re-observe" state updates that re-pointing set
off disappeared with it.

### 2. Reuse views everywhere, not only in scrolling lists

*Sign:* views of a repeated kind (cards, tiles, chips, panels, a detail pane, a popover's content)
are constructed every time their container appears or its content changes: `init`, subview set-up
and constraint activation in the profile, for views identical in structure to ones just thrown away.

List views recycle cells because building a view costs far more than filling one in. That holds for
any view, and nothing outside a list does it for you.

*Move:*

- **Re-point.** Where one item replaces another in the same place, keep the view and hand it the
  new item. Hide it until the new content is in, so the old does not flash.
- **Keep by identity.** When a container's items change, keep the views of the items still there,
  keyed by item id, and build only the difference.
- **Pool.** For a kind that comes and goes, keep the views that leave and take from that pool
  before building. Filling a view in has to overwrite everything the previous item set: content,
  callbacks that point at the old owner, in-flight work, scroll offset, zoom, selection, alpha.
- **Keep chrome for the life of its window.** Toolbar buttons and the like are updated, never
  rebuilt; identity that persists is also what lets them animate between states.

The most expensive case is the web view. Each `WKWebView` is its own process. Attaching one costs
the main thread about 10 ms at first load, plus per-process set-up; on a Mac with many installed
fonts, registering them adds about 20 ms per process. A card per message means that N times over,
and tens of megabytes each. Beyond reusing them: build only the ones on screen, and where several
show static, related content, put them in one process. WebKit does that for a view whose
configuration names a related view, through a private, deprecated property, so guard it, fall back
to a process each, and confirm by counting processes.

### 3. Lay out by hand what repeats, and cache the layout

*Sign:* under the commit, time in the constraint engine (`NSISEngine`, `updateConstraints`,
`layoutSubtreeIfNeeded`, `fittingSize`), in stack views, or in layouts that need several passes to
settle: a wrapping label that must learn its width first, a height reported back that resizes the
container. Text measured twice, once to size an item and again to draw it.

Constraints are solved again for every instance and every pass. For a view that appears once that
is nothing; for one that appears thirty times, or is rebuilt on a hot path, it is a large share of
the stall, and multi-pass layouts are where stale intermediate sizes come from.

*Move:* for each kind of view that repeats, write layout as a pure function from content and
available width to a value: a frame for every subview and the total size. Measure text once, inside
it. The view's layout method only assigns those frames. A list asks the same function for its item
sizes, so sizing and laying out share one computation.

Then cache the value, in one cache shared by every instance:

- **Key it by everything that changes the result:** the item's identity, the width, and every
  displayed field that can change without the identity changing (a formatted date, a flag, a
  badge), plus what changes metrics (font size, scale). A key with too little in it shows up as a
  row laid out for its old content.
- **Let the key do the invalidating.** A new width or new content is a new key; nothing has to be
  cleared. Bound the cache's size.
- A view shown again, a list reloaded, a context returned to, then costs a lookup.

Being pure, the function can be unit-tested, and run ahead of display off the main thread (fix 7).
Leave constraints for the window's skeleton and for one-off screens, where they cost nothing you can
measure, and size hand-laid content to its container so it cannot push the skeleton's constraints
around.

### 4. Do not touch what a framework is animating on its own thread

*Sign:* occasional stalls of 100 to 300 ms with the main thread waiting on a lock under a framework
call, never the same twice.

*Case:* an icon with a repeating SF Symbol effect is drawn on an animation thread. Setting its tint
on every frame of an unrelated slide made the main thread wait for that thread each time.

*Move:* in the sample, find the same class on another thread, then find which of your calls reaches
it and how often. Stop making the call, or replace the mechanism: a Core Animation animation on the
layer is played by the render server with no thread of yours involved. Add it again after the view
is hidden or leaves its window, and skip it under Reduce Motion.

### 5. Make each animation frame nearly free

*Sign:* during an animation, passes exactly one frame apart, each costing several milliseconds.

Animations stepped on the main thread (an animated scroll position, a display link, a SwiftUI
animation in a hosting view) run your observers every frame and then redraw whatever they
invalidated.

*Move:* do nothing when nothing changed. Setters such as tint and text colour invalidate even when
given the value they already hold, and a value blended between two equal endpoints is the same at
every step: detect that once and skip the pass. Let the render server animate what needs no logic
per frame. Budget what is left against 8.3 ms, not 16.7.

### 6. Let animations be redirected mid-flight

*Sign:* the UI trails rapid input, each animation finishing before the next starts; or the second
animation does not happen and the UI jumps to its end state.

*Move:* on new input, stop the animation where it is on screen and animate from there. Do not chain
from completion handlers; that chain is the trailing. If the new target is not laid out, lay it out
beside what is on screen without moving a pixel, then animate.

Two traps cause the jumps:

- **Stale positions.** A layer's presentation value is the last committed frame. After you have
  rearranged things in the same turn, it describes the old arrangement. Stop once, before
  rearranging.
- **Your own notifications.** Code that reacts to "position changed" by settling or snapping is
  also called by the moves you make yourself. A nested call between "rearranged" and "animation
  started" sees a half-finished state and snaps to the end. Do not let the settle code run inside
  itself.

Put the geometry (which pages, what order, what offset) in a pure function and unit-test it.

### 7. Move data work, not view work, off the main thread

Parsing, decoding, database reads, image decoding, diffing, and the layout values of fix 3 (text
measurement included) can move. View creation, assigning frames, drawing and most framework calls
cannot, which is why this comes last.

- **Check which thread the code runs on** in the profile. `async` does not mean background: a task
  started from the main actor stays there, and a nonisolated `async` function may run on its
  caller's actor depending on the language mode.
- **Batch what comes back.** Each delivery to the main thread is a pass with its own layout and
  commit, and in a state-container app an action through every reducer and observer.

## Verify

- The same script, no profiler, slow and fast, against the baseline.
- Film it and step through the frames.
- For anything animated or cached: at least three items, both directions, a gap shorter than the
  animation's visible part and one inside its tail, and the plain action from a middle item.
- Unit-test the pure parts; say which parts are covered only by measurement and film.
- Then let the user try it at their own speed before calling it done.

## Ways to fool yourself

- A baseline taken with the sampler attached, which doubles the "before".
- A profile whose idle filter removed the main thread's deliberate waits.
- Two items in the test data when the bug needs three.
- One direction, at one speed, on film.
- An ease-out that looks finished at a third of its duration while the code still calls it running.
- Frames shrunk so far that a jump reads as fast easing.
- The first visit to a screen after launch, before its content has loaded.
- A second copy of the app running, and the script driving that one.

## Report

Lead with before and after per scenario: worst stall and frames dropped. Then what was wrong and
what changed. Then side effects (state now kept, memory now held). Then, plainly, what is still
slow, with its measured cost, and what was not verified: other refresh rates, more items than the
test data had, devices you did not have. Quote numbers as measured on that machine.

## Limits

Worked out on AppKit with `WKWebView` content on a 60 Hz display. The method carries over to iOS
unchanged; the UIKit specifics above were not exercised, and the timings are one machine's, given
for scale. Fixes 1 and 4 to 6, and re-pointing and process sharing from fix 2, were applied and
measured there. Hand layout with a layout cache is how that app's list rows are built, and a view
pool outside a list was not built; the gain of neither was measured in this work. Where views were
laid out by constraints instead, layout was about a fifth of the main-thread time of opening a set
of cards.
