DEV Community

Cover image for Xcode Instruments in Practice: Profiling and Optimizing iOS Apps
Dheerendra Chaturvedi
Dheerendra Chaturvedi

Posted on

Xcode Instruments in Practice: Profiling and Optimizing iOS Apps

Most performance bugs I've chased in production iOS apps didn't come from code that was obviously slow. They came from code that was fine with test data and fell over with real data. Think of a list that scrolls smoothly with 20 items and stutters with 2,000, or a screen that opens instantly on a new iPhone and takes a second on a three-year-old one. A sort that runs on the main thread "because it's fast", until someone's account has eight years of history.

You can't find these by reading code. You find them by measuring. Xcode Instruments is the tool Apple gives us for that. This article walks through the workflow I use: profile, investigate, optimize, verify. It uses real Swift 6 code and the Instruments features in current Xcode releases.

The performance loop: profile, investigate, optimize, verify

The usual symptoms we're hunting:

  • Slow screen transitions, where a push or sheet animates late or stutters.
  • UI freezes, where the main thread is busy or blocked and taps don't register.
  • High CPU use that drains battery and heats the device.
  • Excessive memory allocations that cause churn, peak-memory spikes, and terminations.
  • SwiftUI view bodies re-evaluating far more often than the data changes.
  • Slow image processing, like decoding full-resolution photos for 60-point thumbnails.
  • Concurrency bottlenecks: tasks queued behind an actor, the main actor flooded with hops, or threads blocked on semaphores.

Understanding Xcode Instruments

Instruments is a profiling tool that comes with Xcode. It records various aspects of your app and the system over time, including CPU samples, allocations, thread states, signposts, and SwiftUI updates. These metrics are displayed as tracks on a shared timeline, allowing you to correlate events like a CPU spike with specific user interactions or system hangs.

You can access Instruments through Product → Profile (⌘I), which builds your app with the scheme's Profile action and launches Instruments attached to it. Alternatively, you can open Instruments from Xcode → Open Developer Tool → Instruments and attach it to a running process.

Instruments versus the Xcode debugger

The debugger provides insights into what is happening at a specific line of code, whereas Instruments helps you understand where time and memory are spent across a complete workflow. Breakpoints can disrupt timing, making them unsuitable for profiling. The debug navigator's CPU and memory gauges indicate that something is expensive but don't specify what. Instruments uses sampling and low-overhead tracing, ensuring your app runs close to real speed while recording.

Profile Release builds

By default, the Profile action uses the Release configuration, which is crucial for accurate profiling. Debug builds compile Swift without optimization (-Onone), so generics aren't specialized, nothing is inlined, and retain/release traffic is much higher. A function that dominates a Debug profile may not appear in a Release build, and the actual bottleneck might not be visible. Always profile using the same configuration you ship, and if you need additional logging or symbols, add them to a Release-based configuration.

Simulator versus physical device

The Simulator runs on your Mac's CPU, memory, GPU, and storage, not on iPhone hardware. Timing data from the Simulator doesn't accurately reflect an iPhone's behavior. Use the Simulator for logic-level checks, such as verifying function calls or detecting leaks. For real profiling, use a physical device, preferably an older model at the lower end of your supported range. This setup provides more accurate insights into thermal state, memory pressure, and GPU behavior.

Choosing the Right Instruments Template

When you start a recording, Instruments asks for a template, which is a preconfigured set of instruments. Picking the right one saves a lot of guesswork.

Template / instrument Use it when… What it shows
Time Profiler Something is slow and the CPU looks busy Sampled call stacks per thread, showing where CPU time goes
Allocations Memory grows, or you suspect allocation churn Every allocation with its call stack, live versus transient counts, generations
Leaks Memory never comes back after leaving a screen Unreachable allocations and retain cycles
Swift Concurrency Tasks feel slow to start, or actors look like bottlenecks Task lifetimes and states, actor queues, which tasks are waiting
SwiftUI Views update too often or bodies are slow View body updates, long updates, and (Xcode 26+) the Cause & Effect Graph
Hangs The UI freezes Main-thread hangs on the timeline, with a configurable threshold
Animation Hitches Scrolling or animations stutter Frames that missed their deadline, and which phase of rendering was late
System Trace A freeze shows low CPU, or you suspect locks or I/O Thread states (running, blocked, waiting), system calls, VM faults, context switches

Time Profiler is the usual starting point. The rest of this article explains when it isn't enough.

Time Profiler: Finding Expensive Functions

Time Profiler samples the call stack of every thread at a fixed interval, typically every millisecond. Functions appearing frequently in samples have consumed significant CPU time. It doesn't trace every call, keeping overhead low enough to profile real workflows.

Here's the routine I follow:

  1. Product → Profile (⌘I). Xcode builds for profiling and opens Instruments.
  2. Choose Time Profiler.
  3. Record a real workflow. Press record, then perform the slow operation in the app: open a screen, scroll a list, apply a filter. Keep the recording short and focused; a 10-second trace of one workflow is better than a 2-minute trace of everything.
  4. Inspect CPU usage. Look for spikes in the CPU track that match your actions. Drag across a spike to set a time range, and the detail area will show only those samples.
  5. Look at the main thread. In the Call Tree options, enable Separate by Thread and expand the main thread. Anything expensive here means your UI couldn't respond.
  6. Read the call stacks. The call tree starts at the root, such as main or a thread's entry point, and branches into callees. Expand the heaviest path (⌥-click the disclosure triangle) to see which of your functions are under the spike.
  7. Enable Hide System Libraries. This collapses UIKit, SwiftUI, Foundation, and the runtime, so the tree shows only your code. Turn it off again when you need to see which framework calls are expensive.
  8. Enable Invert Call Tree. Now the tree starts from the functions that were actually executing when sampled (the leaves) and walks up to their callers. This is the fastest way to find the single most expensive function.
  9. Compare Self Weight and Total Weight (next section).
  10. Identify expensive functions. Sort by weight and double-click a function to open its source with per-line sample counts.

Self Weight versus Total Weight

  • Total Weight is the time spent in a function including everything it called.
  • Self Weight is the time spent in the function's own code, excluding callees.

Take a hypothetical example: a loadFeed() function shows a Total Weight of 900 ms and a Self Weight of 2 ms. loadFeed() itself is cheap, but its callees are expensive. Expand loadFeed() and keep following the heavy branch. Inside, you find decodePosts() (Total 850 ms, Self 15 ms) and under that DateFormatter.date(from:) with a high Self Weight. That's where the CPU burned: you're creating or using a date formatter for every post.

High total with low self means keep drilling down. High self means this function's own work is the cost. In an inverted call tree, the top entries sorted by Self Weight are your hotspots.

Self Weight vs Total Weight in a Time Profiler call tree

Flame Graph and Top Functions

Since Instruments 16 (Xcode 16), call-tree data can also be shown as a Flame Graph. Switch the detail view between Call Tree, Flame Graph and Top Functions from the jump bar above the detail area. Apple introduced it in What's new in Xcode 16.

How to read a flame graph

  • Each box is a function. The width of a box is proportional to how many samples it appeared in, so the share of time.
  • A box sits on top of the function that called it, so a vertical column is one call path.
  • The x-axis is not time. Boxes are grouped by stack, not ordered by when they ran.

You're looking for wide plateaus: a wide box with nothing (or very little) on top of it. Those are functions burning CPU in their own code, the visual equivalent of high Self Weight. A tall, narrow spike is a deep call stack that's cheap overall, so you can usually ignore it.

How to read a flame graph: wide plateaus vs tall narrow stacks

Top Functions

Top Functions flattens the call tree into a list of functions by weight, regardless of where they were called from. This catches a pattern the call tree hides: a small helper called from fifty places. In the call tree its cost is spread across fifty branches and each looks harmless. In Top Functions, it's one row near the top.

A realistic example

Here's a search screen that filters contacts on every keystroke:

struct Contact: Identifiable, Sendable {
    let id: UUID
    let name: String
    let company: String
}

func matches(_ contact: Contact, query: String) -> Bool {
    // Called for every contact on every keystroke.
    let normalizedQuery = query.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
    let haystack = (contact.name + " " + contact.company)
        .folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
    return haystack.contains(normalizedQuery)
}
Enter fullscreen mode Exit fullscreen mode

In the flame graph, the widest plateau sits on String.folding(options:locale:), under matches(_:query:), under the view's filtering code. Top Functions shows folding and the string allocations from + as the top entries. The query is re-normalized once per contact instead of once per keystroke, and every contact's name is re-normalized on every keystroke.

The fix is to normalize each contact once, when contacts load, and the query once per keystroke:

struct SearchableContact: Identifiable, Sendable {
    let contact: Contact
    let searchKey: String          // normalized once
    var id: UUID { contact.id }

    init(_ contact: Contact) {
        self.contact = contact
        self.searchKey = "\(contact.name) \(contact.company)"
            .folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
    }
}

func filter(_ contacts: [SearchableContact], query: String) -> [SearchableContact] {
    guard !query.isEmpty else { return contacts }
    let normalizedQuery = query.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
    return contacts.filter { $0.searchKey.contains(normalizedQuery) }
}
Enter fullscreen mode Exit fullscreen mode

Prioritizing what to optimize

Not every wide box is worth fixing. I rank candidates by three things:

  1. Is it on the main thread during an interaction? Main-thread time during a tap or scroll is felt directly; background time usually isn't.
  2. How wide is it in the selected range? A function taking 3% of a workflow can't save more than 3%.
  3. Is it your code? You can change your code. For framework code, change how often or with what input you call it.

Measuring Specific Operations Using OSSignposter

Time Profiler tells you where CPU goes, but it doesn't pinpoint the duration of specific operations like "open the invoice screen" or distinguish between network wait and decoding times. For that, you need to mark the operation yourself using signposts. OSSignposter (iOS 15+) is the Swift API in the OSLog framework.

import OSLog

enum Signposts {
    // The .pointsOfInterest category puts intervals in Instruments'
    // Points of Interest track, which most templates already include.
    static let app = OSSignposter(
        logHandle: OSLog(subsystem: "com.example.Invoices", category: .pointsOfInterest)
    )
}

struct Invoice: Decodable, Sendable {
    let id: String
    let total: Decimal
    let issuedAt: Date
}

struct InvoiceService: Sendable {
    let session: URLSession
    let baseURL: URL

    func loadInvoices() async throws -> [Invoice] {
        let id = Signposts.app.makeSignpostID()
        let state = Signposts.app.beginInterval("Load invoices", id: id)
        // defer ends the interval on every exit path, including thrown errors.
        defer { Signposts.app.endInterval("Load invoices", state) }

        let (data, _) = try await session.data(from: baseURL.appending(path: "invoices"))
        Signposts.app.emitEvent("Response received", id: id, "\(data.count) bytes")

        return try decodeInvoices(data)
    }

    private func decodeInvoices(_ data: Data) throws -> [Invoice] {
        let state = Signposts.app.beginInterval("Decode invoices", id: Signposts.app.makeSignpostID())
        defer { Signposts.app.endInterval("Decode invoices", state) }

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        return try decoder.decode([Invoice].self, from: data)
    }
}
Enter fullscreen mode Exit fullscreen mode

A few details that trip people up:

  • The interval name must match. beginInterval and endInterval take a StaticString name, and Instruments pairs them by name plus the state from beginInterval.
  • Use a fresh ID for overlapping intervals. makeSignpostID() returns an ID that's unique within the signposter. If two loads can run at once, each needs its own ID, or Instruments can't tell their intervals apart.
  • Dynamic data goes in the message, not the name. Messages use OSLogMessage interpolation, so values are redacted in logs by default but visible in Instruments when you profile.
  • For synchronous blocks there's withIntervalSignpost(_:id:around:), which wraps a closure in an interval.
  • Signposts are cheap when nothing is recording, so they can stay in shipping code. Keep them on meaningful operations, not inside tight loops.

Filtering a recording by signpost interval

Profile with Time Profiler. Your intervals appear in the Points of Interest track (or in an os_signpost track if you add the instrument). Then:

  1. Click an interval, like "Decode invoices", in the track.
  2. Choose Set Inspection Range from its context menu. Every other track's detail view now shows only data from that time range.
  3. The Time Profiler call tree now answers "what was the CPU doing during decoding", without the noise from the rest of the trace.

This is also the key to fair before-and-after comparisons, covered later.

Practical Performance Optimization

The six examples below are realistic but hypothetical. They're patterns I've seen in real apps, simplified for the article. Any timings mentioned are illustrative, not measurements.

A. Moving expensive calculations away from the main thread

The issue. A sales report screen groups and totals thousands of orders. The grouping runs in body, which runs on the main actor, so the screen freezes when it opens and again every time the date range changes.

// Before: heavy work inside body, on the main actor.
struct SalesReportView: View {
    let orders: [Order]
    let range: DateInterval

    var body: some View {
        let rows = ReportBuilder.rows(for: orders, in: range) // runs on every body evaluation
        List(rows) { row in
            LabeledContent(row.day.formatted(date: .abbreviated, time: .omitted),
                           value: row.total, format: .currency(code: "USD"))
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Why it's inefficient. SwiftUI can evaluate body many times, and each evaluation repeats the full grouping on the main thread. With enough orders, one evaluation is longer than a frame, so you get hitches. Past a few hundred milliseconds, it's a hang.

The fix. Compute the rows once per input change, off the main actor, and keep the UI update on the main actor:

nonisolated struct Order: Sendable {
    let date: Date
    let total: Decimal
}

nonisolated struct ReportRow: Identifiable, Sendable {
    let day: Date
    let total: Decimal
    var id: Date { day }
}

nonisolated enum ReportBuilder {
    // Swift 6.2+: @concurrent runs this on the global concurrent executor,
    // never on the caller's actor.
    @concurrent
    static func rows(for orders: [Order], in range: DateInterval) async -> [ReportRow] {
        let calendar = Calendar.current
        var totals: [Date: Decimal] = [:]
        for order in orders where range.contains(order.date) {
            totals[calendar.startOfDay(for: order.date), default: 0] += order.total
        }
        return totals
            .map { ReportRow(day: $0.key, total: $0.value) }
            .sorted { $0.day < $1.day }
    }
}

struct SalesReportView: View {
    let orders: [Order]
    let range: DateInterval
    @State private var rows: [ReportRow]?

    var body: some View {
        Group {
            if let rows {
                List(rows) { row in
                    LabeledContent(row.day.formatted(date: .abbreviated, time: .omitted),
                                   value: row.total, format: .currency(code: "USD"))
                }
            } else {
                ProgressView()
            }
        }
        // Re-runs only when the range changes, and cancels the previous run.
        .task(id: range) {
            let result = await ReportBuilder.rows(for: orders, in: range)
            rows = result // back on the main actor: safe to update view state
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Only the computation moves off the main actor. The view and its @State stay on the main actor, where SwiftUI expects them. Don't move UI updates off the main actor to "speed them up": UIKit and SwiftUI aren't thread-safe, and Swift 6 will (rightly) refuse to compile most attempts.

Notes on the Swift version:

  • Swift 6.2 changed the default. With the nonisolated(nonsending) default (part of Xcode 26's "Approachable Concurrency" settings), a plain nonisolated async function runs on the caller's actor. Without @concurrent, this function would run on the main actor. That's exactly why @concurrent exists.
  • The nonisolated on the types matters if your module uses MainActor default isolation, the default for new Xcode 26 app projects. Without it, Order and ReportBuilder would be inferred as @MainActor.
  • On Swift 6.0 and 6.1, a nonisolated async function already runs off the caller's actor, so drop @concurrent.

Verify. Add a signpost interval around the computation and profile with Time Profiler, filtered to the main thread. The grouping should disappear from the main thread and appear on a cooperative-pool thread. In the Hangs track, opening the screen should no longer produce a hang.

B. Optimizing image loading and processing

The issue. A photo grid decodes each full-resolution image to show a 100-point thumbnail.

// Before
struct PhotoCell: View {
    let imageData: Data
    var body: some View {
        if let image = UIImage(data: imageData) {   // full-size decode on the main actor
            Image(uiImage: image)
                .resizable()
                .scaledToFill()
                .frame(width: 100, height: 100)
                .clipped()
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Why it's inefficient. UIImage(data:) doesn't decode immediately: decoding happens lazily when the image is first rendered, on the main thread. A 12-megapixel photo decodes to about 48 MB (4 bytes per pixel), and you only display about 300×300 pixels of it. Time Profiler shows image-decoding frames under the render pass. Allocations shows large, short-lived image buffers. Apple covers this in Image and Graphics Best Practices (WWDC18).

The fix. Downsample with ImageIO so only a thumbnail-sized bitmap is ever decoded, and do it off the main actor:

import ImageIO
import SwiftUI
import UIKit

nonisolated enum ThumbnailRenderer {
    enum Failure: Error { case unreadableImage }

    /// Decodes only a thumbnail-sized bitmap; the full image is never decoded.
    static func render(_ data: Data, maxPixelSize: Int) throws -> UIImage {
        // Don't cache the full decoded image for the source.
        let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
        guard let source = CGImageSourceCreateWithData(data as CFData, sourceOptions) else {
            throw Failure.unreadableImage
        }
        let thumbnailOptions = [
            kCGImageSourceCreateThumbnailFromImageAlways: true,
            kCGImageSourceCreateThumbnailWithTransform: true,  // respect EXIF orientation
            kCGImageSourceShouldCacheImmediately: true,        // decode now, not at render time
            kCGImageSourceThumbnailMaxPixelSize: maxPixelSize,
        ] as CFDictionary
        guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbnailOptions) else {
            throw Failure.unreadableImage
        }
        return UIImage(cgImage: cgImage)
    }

    @concurrent
    static func thumbnail(from data: Data, maxPixelSize: Int) async throws -> UIImage {
        try render(data, maxPixelSize: maxPixelSize)
    }
}

struct PhotoCell: View {
    let imageData: Data
    @Environment(\.displayScale) private var displayScale
    @State private var thumbnail: UIImage?

    var body: some View {
        ZStack {
            Color.secondary.opacity(0.1)
            if let thumbnail {
                Image(uiImage: thumbnail)
                    .resizable()
                    .scaledToFill()
            }
        }
        .frame(width: 100, height: 100)
        .clipped()
        .task {
            let pixels = Int(100 * displayScale)
            thumbnail = try? await ThumbnailRenderer.thumbnail(from: imageData, maxPixelSize: pixels)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

kCGImageSourceShouldCacheImmediately matters here: without it, the actual decode can still be deferred to render time on the main thread, which undoes the work of moving it off.

Verify. In Time Profiler, image decoding frames should leave the main thread. In Allocations, filter by VM: ImageIO / CG raster data while scrolling. Expect far smaller buffers and a much lower peak. Animation Hitches should show fewer late frames while scrolling.

C. Avoiding unnecessary SwiftUI view updates

The issue. An inbox shows "5 min ago" labels. To keep them fresh, the store publishes the current time every second.

// Before
final class InboxStore: ObservableObject {
    @Published var messages: [Message] = []
    @Published var now = Date()
}

struct InboxView: View {
    @StateObject private var store = InboxStore()

    var body: some View {
        List(store.messages) { message in
            MessageRow(message: message, now: store.now)
        }
        .onReceive(Timer.publish(every: 1, on: .main, in: .common).autoconnect()) {
            store.now = $0
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Why it's inefficient. With ObservableObject, any @Published change sends objectWillChange. Every view observing the store, here the whole inbox, re-evaluates its body every second. Every visible row re-evaluates too, because its now input changed. That's a lot of work to change one label.

The fix. Two changes. Let Text render relative dates itself, so no clock state is needed. And use the Observation framework (@Observable, iOS 17+), which tracks which properties each body reads:

import SwiftUI

struct Message: Identifiable, Sendable {
    let id: UUID
    let sender: String
    let subject: String
    let receivedAt: Date
}

@Observable
final class InboxStore {
    var messages: [Message] = []
    var unreadCount = 0
}

struct InboxView: View {
    @State private var store = InboxStore()

    var body: some View {
        // Reads only `messages`: changes to `unreadCount` don't re-run this body.
        List(store.messages) { message in
            MessageRow(message: message)
        }
    }
}

struct MessageRow: View {
    let message: Message

    var body: some View {
        VStack(alignment: .leading) {
            Text(message.sender).font(.headline)
            Text(message.subject).lineLimit(1)
            // Updates itself as time passes, without re-evaluating this body.
            Text(message.receivedAt, style: .relative)
                .font(.caption)
                .foregroundStyle(.secondary)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Self._printChanges() inside a body is a quick debugging aid that logs what triggered an update. It's underscored and unofficial, so use it only while debugging and remove it before shipping.

Verify. Profile with the SwiftUI template. Before the change, the view body updates track shows InboxView and every visible MessageRow updating once per second while nothing is happening. After it, idle periods should show essentially no body updates. In Xcode 26 and later, the Cause & Effect Graph shows which state change triggered an update. If a view updates more often than you expect, that graph tells you why.

D. Reducing excessive object allocations

The issue. A transactions list creates formatters inside each row's body.

// Before
struct TransactionRow: View {
    let transaction: Transaction

    var body: some View {
        let dateFormatter = DateFormatter()        // new formatter per body evaluation
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .short

        let currencyFormatter = NumberFormatter()  // and another one
        currencyFormatter.numberStyle = .currency
        currencyFormatter.currencyCode = transaction.currencyCode

        return HStack {
            Text(dateFormatter.string(from: transaction.date))
            Spacer()
            Text(currencyFormatter.string(from: transaction.amount as NSDecimalNumber) ?? "")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Why it's inefficient. DateFormatter and NumberFormatter are expensive to create: they load locale and calendar data. Creating two per row per body evaluation, while scrolling, means thousands of short-lived formatters. Time Profiler shows the cost in formatter setup. Allocations shows a large count of transient NSDateFormatter and NSNumberFormatter objects.

The fix. Create the formatter once and reuse it. Views are @MainActor, so a static property on the view is isolated to the main actor too. That keeps a non-Sendable formatter safe under Swift 6 strict concurrency:

struct Transaction: Identifiable, Sendable {
    let id: UUID
    let date: Date
    let amount: Decimal
    let currencyCode: String
}

struct TransactionRow: View {
    let transaction: Transaction

    // Created once, on first use, and reused by every row.
    private static let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        return formatter
    }()

    var body: some View {
        HStack {
            Text(Self.dateFormatter.string(from: transaction.date))
            Spacer()
            // FormatStyle-based formatting: no formatter object to manage.
            Text(transaction.amount, format: .currency(code: transaction.currencyCode))
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The currency side uses FormatStyle (.currency(code:)), which avoids managing a formatter object yourself. Don't assume it's free, though: measure it the same way.

Verify. In Allocations, record a scroll through the list and search for DateFormatter. Before the change, the Transient count climbs with every row. After it, there should be one persistent instance. The Generations feature (Mark Generation before and after the scroll) shows what was allocated during just that workflow.

E. Preventing duplicate asynchronous requests

The issue. A feed shows avatars. Ten rows by the same author appear at once, and each starts its own download of the same URL.

// Before: every caller downloads, even for the same URL at the same moment.
actor AvatarLoader {
    private var cache: [URL: Data] = [:]

    func avatar(for url: URL) async throws -> Data {
        if let cached = cache[url] { return cached }
        let (data, _) = try await URLSession.shared.data(from: url)
        cache[url] = data
        return data
    }
}
Enter fullscreen mode Exit fullscreen mode

Why it's inefficient. This looks safe, because it's an actor, but actors are reentrant. While the first caller is suspended at await URLSession..., the actor accepts the next call. That call also finds the cache empty and starts a second download. The cache only helps after the first download finishes.

The fix. Cache the in-flight task, not just the result, so concurrent callers share one download:

actor AvatarLoader {
    private enum Entry {
        case loading(Task<Data, Error>)
        case loaded(Data)
    }

    private var entries: [URL: Entry] = [:]
    private let session: URLSession

    init(session: URLSession = .shared) {
        self.session = session
    }

    func avatar(for url: URL) async throws -> Data {
        switch entries[url] {
        case .loaded(let data):
            return data
        case .loading(let task):
            return try await task.value          // join the download already in progress
        case nil:
            let session = self.session
            let task = Task { try await session.data(from: url).0 }
            entries[url] = .loading(task)        // recorded before the first suspension
            do {
                let data = try await task.value
                entries[url] = .loaded(data)
                return data
            } catch {
                entries[url] = nil               // let a later call retry
                throw error
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The entry is stored before the first await. That's what makes it work: any call that arrives during the download sees .loading and joins it.

Trade-offs:

  • Cancellation. The download runs in an unstructured Task, so cancelling one caller doesn't cancel it. That's usually what you want, since other callers are waiting, but it means you own cancellation if nobody needs the result anymore.
  • Unbounded cache. This cache never evicts. In a real app, use NSCache or a size limit.

Verify. Profile with the Network instrument (or check your server logs). Ten rows by one author should produce one request, not ten. With Swift Concurrency, you'll also see far fewer download tasks.

F. Improving actor-based concurrency

The issue. A thumbnail store does CPU-heavy rendering inside the actor.

// Before
actor ThumbnailStore {
    private var cache: [URL: UIImage] = [:]

    func thumbnail(for url: URL, maxPixelSize: Int) async throws -> UIImage {
        if let cached = cache[url] { return cached }
        let (data, _) = try await URLSession.shared.data(from: url)
        let image = try ThumbnailRenderer.render(data, maxPixelSize: maxPixelSize) // runs on the actor
        cache[url] = image
        return image
    }
}
Enter fullscreen mode Exit fullscreen mode

Why it's inefficient. An actor runs one piece of isolated code at a time. ThumbnailRenderer.render is synchronous and runs while the actor is held, so twenty thumbnails render one after another even on a six-core phone. Every other call, including instant cache hits, waits behind the current render. In the Swift Concurrency instrument, this shows up as a long queue of tasks waiting on ThumbnailStore. In Time Profiler, only one thread is busy rendering.

The fix. Keep the actor for what it's good at, protecting the cache, and do the heavy work outside it:

actor ThumbnailStore {
    private var cache: [URL: UIImage] = [:]

    func thumbnail(for url: URL, maxPixelSize: Int) async throws -> UIImage {
        if let cached = cache[url] { return cached }

        let (data, _) = try await URLSession.shared.data(from: url)
        // Runs on the concurrent executor; the actor is free while it renders.
        let image = try await ThumbnailRenderer.thumbnail(from: data, maxPixelSize: maxPixelSize)

        // Reentrancy: another call may have filled the cache while we were suspended.
        if let cached = cache[url] { return cached }
        cache[url] = image
        return image
    }
}
Enter fullscreen mode Exit fullscreen mode

The re-check after the await matters. Any await inside an actor is a point where other calls can run and change its state. Re-validate assumptions after every suspension. Combine this with the in-flight pattern from E if duplicate downloads also matter.

Verify. In the Swift Concurrency instrument, the actor's queue should stay short. In Time Profiler (Separate by Thread), rendering should spread across several threads. Wrap a batch of thumbnails in a signpost interval and compare its duration before and after. On the same device and with the same images, the interval should shrink.

Understanding Swift Concurrency Performance

Swift concurrency changes what a bottleneck looks like. These are the concepts that matter most when reading a profile.

MainActor Contention

The main actor is one serial executor. Every await MainActor.run, every @MainActor method call from a background task, and every UI update queues on it. Each hop is cheap, but thousands of them compete with rendering and touch handling.

// Before: one main-actor hop per item.
@concurrent
func importRecords(_ records: [Record], progress: @MainActor @Sendable (Int) -> Void) async {
    for (index, record) in records.enumerated() {
        process(record)
        await progress(index + 1)     // 10,000 records → 10,000 hops to the main actor
    }
}

// After: report progress in batches.
@concurrent
func importRecords(_ records: [Record], progress: @MainActor @Sendable (Int) -> Void) async {
    for (index, record) in records.enumerated() {
        process(record)
        if (index + 1).isMultiple(of: 250) || index == records.count - 1 {
            await progress(index + 1)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

(Record and process(_:) stand for your own model type and work function.)

Actor Execution and Reentrancy

Actors serialize execution, not operations. An actor method that awaits can be interleaved with other calls at each await, as in example E. Performance-wise, two rules follow:

  • Don't do long synchronous work inside an actor. It blocks every other caller (example F).
  • Treat every await inside an actor as a point where state may change. Re-check after it.

Task Scheduling, Unstructured Tasks, and Excessive Task Creation

Task { } creates an unstructured task. It inherits the current actor and priority, isn't cancelled with its parent, and nothing waits for it. Creating one per item for a large collection gives you thousands of tasks competing for the cooperative thread pool, which has about one thread per CPU core. That means memory overhead, and work finishing in an unpredictable order.

For "do this for every item," use a task group with bounded concurrency:

nonisolated enum ThumbnailBatch {
    /// Renders thumbnails with at most `maxConcurrent` renders in flight.
    static func render(
        _ items: [(url: URL, data: Data)],
        maxPixelSize: Int,
        maxConcurrent: Int = 4
    ) async -> [URL: UIImage] {
        await withTaskGroup(of: (URL, UIImage?).self) { group in
            var results: [URL: UIImage] = [:]
            var pending = items.makeIterator()

            func addNext() {
                guard let item = pending.next() else { return }
                group.addTask {
                    (item.url, try? ThumbnailRenderer.render(item.data, maxPixelSize: maxPixelSize))
                }
            }

            for _ in 0..<maxConcurrent { addNext() }
            while let (url, image) = await group.next() {
                results[url] = image
                addNext()
            }
            return results
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Structured child tasks are cancelled with their parent, their results are collected in one place, and the limit keeps memory predictable. Each in-flight render holds a decoded bitmap.

Background Processing

@concurrent functions, Task.detached and the cooperative pool are for CPU work that finishes. Long-running or blocking work, like large synchronous file I/O or a C library that blocks, doesn't belong on the cooperative pool, because it holds a thread that other tasks need. For blocking work, use a dedicated DispatchQueue or Thread and bridge back with a continuation.

Thread Blocking versus Asynchronous Suspension

This is the most important distinction for reading profiles:

  • Suspension (await) gives the thread back. Other tasks run on it while you wait.
  • Blocking (DispatchSemaphore.wait(), Thread.sleep, a synchronous lock held across slow work) keeps the thread and does nothing with it.

Suspension vs blocking on a cooperative-pool thread

// Don't: blocks a cooperative-pool thread, and can deadlock if
// the work it waits for needs that same pool.
func loadSync(_ url: URL) -> Data? {
    let semaphore = DispatchSemaphore(value: 0)
    var result: Data?
    Task {
        result = try? await URLSession.shared.data(from: url).0
        semaphore.signal()
    }
    semaphore.wait()
    return result
}

// Do: suspend instead of blocking.
func load(_ url: URL) async throws -> Data {
    try await URLSession.shared.data(from: url).0
}
Enter fullscreen mode Exit fullscreen mode

Don't count on the compiler to catch this. Swift 6 happens to reject this exact snippet because the task mutates a captured var, but wrap the result in a lock-protected box and it compiles cleanly: blocking itself is never a compile error. In a trace, it shows up as a thread in a blocked state in System Trace, and in Time Profiler as a thread that's alive but has almost no samples.

The WWDC sessions Swift concurrency: Behind the scenes and Visualize and optimize Swift concurrency go deeper on the thread pool and the Swift Concurrency instrument.

Verifying Improvements with Run Comparisons

An optimization isn't done until you've measured it on the same workflow, on the same device, under the same conditions.

The routine

  1. Capture a baseline. Profile the workflow before changing anything. Wrap it in a signpost interval ("Open report") so you can isolate it later.
  2. Apply one optimization. Just one. If you change three things, you won't know which one helped or which one regressed.
  3. Capture another recording of the same workflow: same device, same data, same steps. Let the device cool down between runs, and keep other apps closed.
  4. Compare equivalent ranges. Set the inspection range to the signpost interval in both runs, so you compare "open report" with "open report", not two arbitrary time windows.
  5. Interpret the result.

Instruments keeps multiple runs in one trace document: record again, and the new run appears next to the old one. Since Xcode 26.4, you can compare call trees between runs directly. Use View → Detail Area → Compare With… or the ⇆ button in the jump bar. Functions that got slower are marked as regressions and functions that got faster as improvements. You can also bring recordings into one document with File → Import As Run…. See the Xcode 26.4 release notes and Profile, fix, and verify: Improve app responsiveness with Instruments (WWDC26).

Interpreting improvements and regressions

  • Look for the cost moving, not just shrinking. Moving work off the main thread (example A) shouldn't reduce total CPU much, but main-thread time during the interaction should drop. If total CPU rises noticeably, you may have added overhead, such as extra copies or task creation.
  • Check the other tracks. A faster Time Profiler run with a new spike in Allocations, or a new hang, is a trade, not a win.
  • Single runs are noisy. Record the workflow several times per variant and look at the spread before trusting a small difference.

Example comparison

The numbers below are illustrative only, made up to show how to lay out a comparison, not measurements from a real app.

Metric (same workflow, same device) Baseline After optimization What to look at
"Open report" signpost interval 1,200 ms 350 ms Total user-visible duration
Main-thread CPU during interval 1,050 ms 40 ms Should drop sharply when work moves off main
Total CPU during interval 1,100 ms 1,080 ms Roughly the same is expected; a big rise is a warning
Hangs reported 1 0 Should disappear
Transient DateFormatter allocations 2,400 1 Allocations, Generations view
Peak memory 310 MB 120 MB Allocations / VM Tracker

When Time Profiler Is Not Enough

Time Profiler only sees threads that are running. Many performance issues occur when threads are not running:

  • Hangs reveal when the main thread is unresponsive and for how long. Start here for "the app froze" reports. The instrument lets you configure the hang threshold. Apple's Identifying a hang tutorial walks through distinguishing a busy main thread from a blocked one.
  • System Trace displays thread states: running, runnable (waiting for a CPU), blocked (waiting on a lock, I/O, or another thread), and the system calls and virtual-memory faults involved. Use it when a hang shows low CPU usage, or when lock contention or file I/O is suspected.
  • Allocations helps answer memory questions: what's allocated, by whom, how much is transient, and whether memory returns to baseline after leaving a screen.
  • Leaks detects memory that no longer has references, typically due to retain cycles between closures and self. Remember that a leak only appears after the objects become unreachable, so exercise the screen and leave it.
  • Swift Concurrency shows task states and actor queues: tasks created, running, suspended, or waiting on an actor. Use it when async work is slow to start rather than slow to run.

Low CPU during a freeze

If the UI is frozen but the CPU track is nearly flat, the main thread isn't doing expensive work; it's waiting. Common causes include:

  • A DispatchQueue.main.sync or semaphore wait on the main thread
  • A lock held by a background thread
  • Synchronous file or database I/O
  • A synchronous IPC call to a system service

Time Profiler shows little activity because there's little to sample. System Trace reveals the main thread in a blocked state and what it's waiting on. Apple describes this "blocked main thread" pattern in Analyze hangs with Instruments (WWDC23).

Production Performance Profiling Checklist

Before a release, I run through this list:

  • [ ] Profile Release builds on a physical device, including the oldest device you support.
  • [ ] Use production-sized data: real account sizes, long histories, large images.
  • [ ] Record the critical workflows: launch, first screen, main list scroll, search, the heaviest detail screen.
  • [ ] Time Profiler: ensure there's no unexpected main-thread work during interactions.
  • [ ] Hangs: no hangs in critical workflows.
  • [ ] Animation Hitches: scrolling and key transitions should be smooth; no hitches.
  • [ ] Allocations: memory should return to baseline after leaving screens; no runaway transient allocations; acceptable peak memory.
  • [ ] Leaks: none after navigating through and away from major screens.
  • [ ] SwiftUI: no views updating far more often than their data changes.
  • [ ] Swift Concurrency: no actor with a long queue, no unbounded task creation.
  • [ ] Signposts around key operations, so regressions are measurable next time.
  • [ ] Baseline recordings saved, to compare against in the next release.
  • [ ] Check Xcode Organizer for hang, launch, and memory reports from users after release. Real devices in the field often reveal issues that your test devices miss.

Conclusion

The workflow is the same regardless of the symptom:

  • Profile a real workflow on a real device.
  • Investigate with the instrument that matches the symptom.
  • Optimize the one thing the data points to.
  • Verify with a comparable recording.

Most fixes in this article are small. The challenge lies in identifying which small change matters, and Instruments is the tool that provides that insight.

Optimizing without measuring can lead to mistakes in both directions. You might spend a day speeding up code that wasn't the issue, or release a "faster" version that merely shifts the cost elsewhere. A recording, however, costs just a few minutes and definitively answers the question.

FAQ

What is Xcode Instruments used for?
Instruments is Apple's profiling app, included with Xcode. It records CPU usage, memory allocations, leaks, hangs, SwiftUI updates, Swift concurrency activity, and more on a shared timeline, helping you identify what makes an app slow or memory-hungry.

Should I profile in the Simulator or on a device?
For timing-related profiling, use a physical device. The Simulator runs on your Mac's hardware, so its timings don't reflect iPhone performance accurately. It's still useful for logic checks, such as call counts or memory leaks.

What's the difference between Self Weight and Total Weight in Time Profiler?
Total Weight includes the time spent in the functions a function calls. Self Weight counts only the function's own code. If the Total Weight is high but the Self Weight is low, the cost is likely deeper in the call tree. If the Self Weight is high, the function itself is expensive.

How do I measure one specific operation in Instruments?
Wrap the operation in an OSSignposter interval (beginInterval / endInterval), using a signposter with the .pointsOfInterest category. The interval will appear in the Points of Interest track, and you can set it as the inspection range to filter other instruments to that operation.

Why does my app freeze when Time Profiler shows low CPU?
The main thread might be blocked, not busy, due to waiting on a lock, a semaphore, synchronous I/O, or another thread. Use the Hangs instrument to find the freeze, and System Trace to see what the main thread was waiting for.

References

Top comments (0)