Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 46 ยท Concurrency and Performance

Performance, Instruments and Smooth Scrolling

Find and fix slow SwiftUI screens: keep body cheap, use lazy containers, downsample images, read hitches in Instruments and track down memory leaks.

Users rarely say "the main thread was blocked for 40 milliseconds." They say the app feels sluggish. Smoothness is one of the most noticeable parts of an iOS app, and it comes down to a simple deadline: on a 60 Hz screen a new frame is due every 16.7 milliseconds, and on a 120 Hz ProMotion screen every 8.3 milliseconds. If your app misses the deadline, the previous frame stays on screen a little longer, and the user sees a stutter. Apple calls such a missed frame a hitch.

This lesson shows where SwiftUI apps typically lose time, how to fix each cause, and how to measure with Instruments so you fix the right thing. It builds on concurrency in iOS and on the pitfalls in common SwiftUI mistakes. Instruments and SwiftUI cannot run on this site, so those parts are read-only. The runnable examples are small stand-ins that count work instead of timing it. Counts are exact and repeatable, while timings on a shared server are not.

Where frames get lost

Heavy body Slow work while building views.
Eager lists Building rows nobody sees.
Big images Decoding huge pictures.
Leaks Memory that never frees.

Measure first, then fix the biggest one.

1 / 2

Keep body cheap

SwiftUI calls a view's body whenever the state it reads changes, and it may call it often: every frame of an animation, every keystroke in a text field. The result of body is a lightweight description, so building it should take microseconds. Trouble starts when body itself does real work.

Things that do not belong in body (or in code that body calls on every pass):

  • creating a DateFormatter or NumberFormatter, which is surprisingly expensive,
  • sorting or filtering a large array,
  • parsing JSON or reading files,
  • anything that loops over thousands of items.

The fix is almost always the same: do the work once, keep the result, and only redo it when the inputs change. Put the work in a model (see @Observable models), cache it, or create the formatter once as a static constant.

The stand-in below counts how many formatters are created when a 200-row list is rendered three times. It also shows a cache that recomputes a sorted array only when the data changes. The nonisolated(unsafe) on the counters is test scaffolding that lets plain helper functions update them.

Swift Count the work: creating vs reusing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The slow version creates 600 formatters for three renders. The fast version creates a single shared formatter and none while rendering. The cached model sorts twice in ten reads, once at the start and once after the change. In a real list scrolling at 120 frames per second, the difference between "work per frame" and "work per change" is the difference between smooth and stuttering.

Other body-level habits

  • Make body a pure function of state. No network calls, no random numbers, no Date() that makes every pass differ.
  • Split big views into smaller ones. A small view that reads only the state it needs is re-evaluated alone when that state changes. A giant view reading everything is rebuilt as a whole.
  • Prefer stable identity. In a ForEach, use Identifiable models with stable ids, not array indices or random UUIDs created inside body. Unstable ids make SwiftUI throw away and rebuild rows. See lists and ForEach.
  • Avoid AnyView in hot paths. It hides the view type from SwiftUI, which makes comparing old and new views harder. Prefer @ViewBuilder, Group or generic views.
  • Debug with Self._printChanges(). Calling it at the top of body prints what caused a re-evaluation. It is a debugging aid, so remove it afterwards.

Lazy containers for long content

A VStack inside a ScrollView builds every child, even those far off screen. For ten rows, that is fine. For ten thousand, startup freezes and memory balloons. The lazy containers build rows only when they are about to appear:

Swift
ScrollView {
    LazyVStack(spacing: 12) {
        ForEach(messages) { message in
            MessageRow(message: message)
        }
    }
}

List is lazy by default, and LazyVGrid and LazyHGrid are the lazy versions of grids. The cost of laziness is that scroll positions and total sizes are estimated while you scroll, so use stable row heights where you can, and do not put the lazy container in a parent that forces it to its full height (a ScrollView nested in a ScrollView).

Swift Eager vs lazy: how many rows get built?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The eager approach builds 10,000 rows to show 14 of them. The lazy version builds 14 at launch and only the rows it actually reaches afterwards. (A real lazy container also keeps a few rows beyond the edges so scrolling feels smooth. The idea is the same.)

Images: the biggest memory trap

A JPEG file of a few hundred kilobytes can look innocent. But to draw it, the system must decode it into raw pixels, and that takes width x height x 4 bytes (red, green, blue and alpha, one byte each), whatever the file size was. A 12-megapixel photo (4032 by 3024) decodes to about 46 MB. A grid of 100 of them would need roughly 4.5 GB, which is far more than an iPhone will give your app. The app is terminated for using too much memory.

The solution is downsampling: decode a small version sized for how it will be displayed. The ImageIO framework can create a thumbnail without ever decoding the full image:

Swift
import ImageIO
import UIKit

func downsampledImage(at url: URL, maxPixelSize: CGFloat) -> UIImage? {
    let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
    guard let source = CGImageSourceCreateWithURL(url as CFURL, sourceOptions) else { return nil }

    let options = [
        kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceShouldCacheImmediately: true,
        kCGImageSourceCreateThumbnailWithTransform: true,
        kCGImageSourceThumbnailMaxPixelSize: maxPixelSize,
    ] as CFDictionary

    guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, options) else { return nil }
    return UIImage(cgImage: thumbnail)
}

This is a read-only sketch. Set maxPixelSize to the display size in pixels, so points multiplied by the screen scale. Do this work off the main actor, and cache the result. For images from the network, AsyncImage is fine for simple cases, but a long scrolling feed usually needs its own cache with downsampling. The next stand-in does the arithmetic.

Swift Why decoded size matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

One thumbnail is about 0.2 MB, and a hundred of them about 16.5 MB. The picture looks the same in an 80-point cell, because the cell can only show 240 pixels across anyway.

Measuring with Instruments

Guessing about performance is a trap. Instruments is Xcode's profiler, and it shows what your app really does. Choose Product > Profile (Command-I), pick a template, record while you use the app, then stop and study the result.

Rules for honest measurements:

  • Use a real device. The simulator runs on your Mac's CPU and memory, so it hides problems that appear on a phone.
  • Profile a Release build. The Profile action does this by default. Debug builds skip optimizations and can look much slower than what users get.
  • Test the oldest device you support, with realistic data (thousands of rows, big photos), not three demo items.
  • Change one thing, measure again.

The instruments you will use most:

  • Time Profiler samples what your code is doing many times a second. A function that appears in many samples is where time goes. Use the call tree with "Hide system libraries" to see your own code first, and look at the heaviest stack on the main thread.
  • SwiftUI instrument shows how often views update and how long their body evaluations take, so you can find views that update too often or take too long.
  • Hangs and Animation Hitches (the Hitches template) shows frames that missed their deadline, and what the main thread was doing at the time. A hang is a longer freeze, when the main thread is unresponsive for a noticeable moment.
  • Allocations shows memory growth and which code allocates it. Leaks finds objects that are no longer reachable but never freed.

For problems you cannot reproduce yourself, Xcode's Organizer and MetricKit report launch time, hangs and memory use from real users' devices.

Memory leaks

ARC frees an object when nothing points to it strongly. A retain cycle happens when two objects point at each other, or when an object stores a closure that captures it. Neither can be freed, so memory grows each time the screen is opened. A classic cause is a closure property that uses self strongly.

Swift A retain cycle vs a weak capture

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The leaky screen never prints deinit, which is the clearest sign of a cycle: if deinit never runs when you leave a screen, something holds on to it. The weak version is freed as soon as the scope ends, and a closure that outlives it sees nil and returns safely. Not every closure needs [weak self], because a closure that is not stored by the object it captures creates no cycle. The pattern to watch for is an object that stores a closure referring back to it, as well as delegates (declare them weak) and timers or observers that you forget to remove. SwiftUI structs are values and rarely leak by themselves, but the classes they use, such as view models, can.

To find leaks in Xcode, use the Memory Graph debugger (the button in the debug bar) after navigating to a screen and back: instances that should be gone but remain, with a purple exclamation mark, usually point to a cycle. Instruments' Leaks and Allocations tools tell the same story over time.

A short checklist

  1. Is anything slow inside body? Move it to a model or cache it.
  2. Do long lists use List or lazy stacks, with stable ids?
  3. Are images downsampled to their display size and cached?
  4. Is heavy work off the main actor?
  5. Have you recorded on a real device, with a release build, using realistic data?
  6. Does every screen free its memory when you leave it?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. At 120 Hz, roughly how long does your app have to produce each frame?

    120 Hz means 120 frames per second, so about 8.3 ms per frame. At 60 Hz the budget is about 16.7 ms.
  2. 2. Which of these is the biggest problem inside a SwiftUI view's body?

    Body can run very often. Expensive creation and sorting there is repeated each time, so do it once in a model or cache.
  3. 3. A 4032 x 3024 photo is shown in a small grid cell. Why can it use so much memory?

    The decoded bitmap is about 46 MB for that photo. Downsampling to the display size avoids it.
  4. 4. Where should you measure performance?

    Simulator and debug builds hide or distort problems. Profile a release build on real hardware, ideally the oldest device you support.
  5. 5. A screen's deinit never prints after you leave the screen. What is the most likely cause?

    An object is freed only when nothing owns it. A closure stored on the object that captures self strongly is a classic cycle; [weak self] breaks it.

Summary

  • A frame is due every 16.7 ms (60 Hz) or 8.3 ms (120 Hz); missing it causes a hitch, and a long freeze is a hang.
  • Keep body cheap: no formatter creation, sorting, parsing or loops over big data; compute once in a model and cache.
  • Use List or lazy stacks and grids for long content, with stable ids.
  • Decoded images cost width x height x 4 bytes; downsample to display size with ImageIO and cache the result.
  • Measure with Instruments on a real device using a release build: Time Profiler, the SwiftUI instrument, Hitches, Allocations and Leaks.
  • A retain cycle (often a stored closure capturing self) keeps objects alive; break it with [weak self] or weak delegates, and check deinit and the Memory Graph.

Next: Animations and Transitions