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 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:
- Product → Profile (⌘I). Xcode builds for profiling and opens Instruments.
- Choose Time Profiler.
- 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.
- 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.
- 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.
- Read the call stacks. The call tree starts at the root, such as
mainor 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. - 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.
- 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.
- Compare Self Weight and Total Weight (next section).
- 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.
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.
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) } 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) } } Prioritizing what to optimize
Not every wide box is worth fixing. I rank candidates by three things:
- 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.
- How wide is it in the selected range? A function taking 3% of a workflow can't save more than 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) } } A few details that trip people up:
- The interval name must match.
beginIntervalandendIntervaltake aStaticStringname, and Instruments pairs them by name plus the state frombeginInterval. - 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
OSLogMessageinterpolation, 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:
- Click an interval, like "Decode invoices", in the track.
- Choose Set Inspection Range from its context menu. Every other track's detail view now shows only data from that time range.
- 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")) } } } 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 } } } 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 asyncfunction runs on the caller's actor. Without@concurrent, this function would run on the main actor. That's exactly why@concurrentexists. - The
nonisolatedon the types matters if your module uses MainActor default isolation, the default for new Xcode 26 app projects. Without it,OrderandReportBuilderwould be inferred as@MainActor. - On Swift 6.0 and 6.1, a
nonisolated asyncfunction 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() } } } 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.secondarySource:https://dev.to/dhee161286/xcode-instruments-in-practice-profiling-and-optimizing-ios-apps-2g2h Related posts

PostgreSQL 19 removes the MultiXact members wall. Reclamation still waits for template0.
Hugging Face Breach: Security Lessons for AI Agents
Incus Project and Migration Trust Boundaries Need Separate Review

Next.js `revalidatePath` vs `revalidateTag` in 2026: Choosing the Right Cache Invalidation Primitive at Scale



