Generated banner for Performance Profiling
Generated logo for Performance Profiling

Performance Profiling

Meng ToCommunityCreated by Meng To

  • Skill
  • Guidelines
  • Software development
  • MIT
  • No issues found

From the author

Guide performance profiling for Apple platform apps with Instruments, Xcode diagnostics, and MetricKit. Use when investigating app hangs, stutters, high CPU, memory leaks, memory growth, OOM crashes, slow launch, battery drain, thermal issues, App Store performance readiness, or when adding os_signpost and measurement hooks.
— the description by Meng To

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to performance profiling for Apple platform apps. It helps developers identify bottlenecks related to CPU usage, memory management, launch times, and energy consumption. By leveraging Xcode instruments, diagnostics, and MetricKit, the skill guides users through a repeatable workflow: identifying the performance category, profiling on physical hardware, applying targeted fixes, and verifying improvements with concrete measurements.

What it does

  • Provides a decision tree to match performance issues with the correct diagnostic tool.
  • Outlines a systematic workflow for profiling, fixing, and verifying performance improvements.
  • Offers specific guidance for CPU, memory, launch time, and energy diagnostics.
  • Recommends Xcode diagnostic settings to detect common runtime issues.
  • Provides code patterns for integrating MetricKit to monitor production performance.
  • Includes a review checklist for responsiveness, memory, launch, and energy best practices.

When to use it

  • When investigating app hangs, stutters, or high CPU usage.
  • When troubleshooting memory leaks, growth, or OOM crashes.
  • When optimizing cold, warm, or resume launch times.
  • When addressing battery drain, thermal throttling, or excessive network usage.
  • When preparing an application for App Store performance readiness.

Advantages

  • Promotes data-driven optimization by prioritizing real-device profiling.
  • Reduces guesswork by mapping specific symptoms to dedicated profiling tools.
  • Encourages sustainable performance through production monitoring with MetricKit.
  • Provides actionable code examples for common performance pitfalls.
  • Standardizes the process of verifying fixes before and after implementation.

Usage examples

“My app is experiencing high CPU usage. How should I investigate?”
The skill directs you to use the Time Profiler instrument, focus on CPU percent by function, and check the call tree weight to identify the specific code path causing the bottleneck.
“How can I reduce my app's cold launch time?”
The skill suggests using the App Launch instrument, reducing dynamic frameworks, removing static initializers, and deferring non-essential initialization code in the app's entry point.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/mengto/performance-profiling/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip performance-profiling.zip -d .agents/skills

Documentation by Meng To

Performance Profiling

Use this skill to diagnose Apple app performance issues systematically, pick the right profiling workflow, apply targeted fixes, and verify the change with real measurements.

Decision Tree

Choose the reference file before changing code:

What performance problem are you investigating?

+ App hangs, stutters, dropped frames, slow UI, high CPU
  -> Read references/time-profiler.md

+ High memory, leaks, OOM crashes, growing footprint
  -> Read references/memory-profiling.md

+ Slow cold launch, warm launch, resume, or time to first frame
  -> Read references/launch-optimization.md

+ Battery drain, thermal throttling, background energy, network waste
  -> Read references/energy-diagnostics.md

+ General "app feels slow"
  -> Start with references/time-profiler.md, then references/memory-profiling.md

+ Pre-release performance audit
  -> Read all reference files and use the review checklist below

Quick Reference

ProblemInstrument / ToolKey MetricReference
UI hangs over 250 msTime Profiler + HangsHang duration, main thread stackreferences/time-profiler.md
High CPU usageTime ProfilerCPU percent by function, call tree weightreferences/time-profiler.md
Memory leakLeaks + Memory GraphLeaked bytes, retain cycle pathsreferences/memory-profiling.md
Memory growthAllocationsLive bytes, generation analysisreferences/memory-profiling.md
Slow launchApp LaunchTime to first frame, pre-main, post-mainreferences/launch-optimization.md
Battery drainEnergy LogEnergy impact, CPU/GPU/network activityreferences/energy-diagnostics.md
Thermal issuesActivity Monitor, InstrumentsThermal state transitionsreferences/energy-diagnostics.md
Network wasteNetwork profilerRedundant fetches, payload sizereferences/energy-diagnostics.md

Workflow

  1. Identify the performance category from the user report, traces, logs, or code path.

  2. Read only the matching reference file unless the issue is broad or unclear.

  3. Prefer real device profiling with a Release build and representative data.

  4. Inspect the code path named by the profile before proposing a fix.

  5. Apply the smallest targeted fix that addresses the measured bottleneck.

  6. Re-profile or add a repeatable measurement to confirm the improvement.

Profiling Ground Rules

  • Profile on device when possible; Simulator uses host CPU and memory.

  • Use Release configuration because optimizations can change hot paths.

  • Reproduce with representative data, not empty databases or toy assets.

  • Close unrelated apps to reduce noise during profiling.

  • Keep measurements before and after the fix so the outcome is concrete.

  • Add os_signpost markers when a workflow needs ongoing timing visibility.

Xcode Diagnostics

Recommend relevant Scheme > Run > Diagnostics settings when they match the suspected issue:

SettingUse For
Main Thread CheckerUI work off the main thread
Thread SanitizerData races and unsafe shared state
Address SanitizerBuffer overflows and use-after-free
Malloc Stack LoggingAllocation call stacks
Zombie ObjectsMessages to deallocated objects

MetricKit Hook

Suggest MetricKit for production monitoring of launch, responsiveness, memory, and diagnostics:

import MetricKit

final class PerformanceReporter: NSObject, MXMetricManagerSubscriber {
    func startCollecting() {
        MXMetricManager.shared.add(self)
    }

    func didReceive(_ payloads: [MXMetricPayload]) {
        for payload in payloads {
            if let launch = payload.applicationLaunchMetrics {
                log("Resume time: \(launch.histogrammedResumeTime)")
            }
            if let responsiveness = payload.applicationResponsivenessMetrics {
                log("Hang time: \(responsiveness.histogrammedApplicationHangTime)")
            }
            if let memory = payload.memoryMetrics {
                log("Peak memory: \(memory.peakMemoryUsage)")
            }
        }
    }

    func didReceive(_ payloads: [MXDiagnosticPayload]) {
        for payload in payloads {
            if let hangs = payload.hangDiagnostics {
                for hang in hangs {
                    log("Hang: \(hang.callStackTree)")
                }
            }
        }
    }
}

Review Checklist

Responsiveness:

  • No synchronous work on the main thread over 100 ms.

  • No file I/O or network calls on the main thread.

  • Large Core Data or SwiftData fetches use background contexts.

  • Images decode off the main thread.

  • @MainActor is limited to code that truly needs UI access.

Memory:

  • No retain cycles in delegates, closures, observers, or async tasks.

  • Large resources are released when no longer visible.

  • Collections and caches are bounded.

  • autoreleasepool is used in tight loops that create Objective-C objects.

Launch:

  • No heavy work in init() of the @main App struct.

  • Non-essential initialization is deferred.

  • Dynamic frameworks are minimized where practical.

  • No synchronous network calls occur during launch.

Energy:

  • Background tasks use the appropriate BGTaskScheduler request type.

  • Location accuracy matches the product need.

  • Timers use tolerance so the system can coalesce wakeups.

  • Network requests are batched and cached where possible.

References

  • references/time-profiler.md: CPU profiling, hang detection, signpost API.

  • references/memory-profiling.md: Allocations, Leaks, Memory Graph debugger.

  • references/launch-optimization.md: Launch phases and cold/warm start optimization.

  • references/energy-diagnostics.md: Battery, thermal state, and network efficiency.

Files

references/memory-profiling.md

Memory Profiling

Contents

  • Instruments Setup

  • Allocations Instrument

  • Leaks Instrument

  • Xcode Memory Graph Debugger

  • Autorelease Pool Optimization

  • Memory Footprint Tracking in Code

  • Quick Diagnosis Checklist

Instruments Setup

Allocations Instrument
  1. Xcode > Product > Profile (Cmd+I)

  2. Choose Allocations template

  3. Record, reproduce the issue, stop

Leaks Instrument
  • Included in the Allocations template by default

  • Runs periodic scans for unreachable memory

  • Red crosses in the Leaks lane indicate detected leaks

Allocations Instrument

Key Metrics
MetricMeaning
All Heap AllocationsTotal memory allocated on the heap
Live BytesCurrently allocated (not freed) memory
Transient BytesAllocated and freed during recording
# LivingCount of live allocation objects
# TransientCount of freed allocations
Reading the Results
  • Sort by Live Bytes to find largest memory consumers

  • Sort by # Living to find most numerous allocations

  • Click a category to see individual allocations with stack traces

  • Persistent column shows objects that survive across generations

Generation Analysis (Mark Generation)

Track memory growth over repeated operations:

  1. Start recording

  2. Click Mark Generation to baseline

  3. Perform an operation (open screen, load data, etc.)

  4. Click Mark Generation again

  5. Repeat the same operation

  6. Compare generations - growth between identical operations = leak or unbounded cache

What to look for:

  • Stable: Each generation has similar Live Bytes

  • Leaking: Each generation grows - objects from previous generations persist

  • Caching: Growth that plateaus after a few generations (may be intentional)

Common Memory Issues
Unbounded Cache Growth
// Bad - cache grows forever
class ImageCache {
    var cache: [URL: UIImage] = [:]

    func image(for url: URL) -> UIImage? {
        return cache[url]
    }
}

// Good - use NSCache for automatic eviction
class ImageCache {
    private let cache = NSCache<NSURL, UIImage>()

    init() {
        cache.countLimit = 100
        cache.totalCostLimit = 50 * 1024 * 1024 // 50 MB
    }

    func image(for url: URL) -> UIImage? {
        return cache.object(forKey: url as NSURL)
    }

    func store(_ image: UIImage, for url: URL) {
        let cost = image.cgImage.map { $0.bytesPerRow * $0.height } ?? 0
        cache.setObject(image, forKey: url as NSURL, cost: cost)
    }
}
Large Images Not Downsampled
// Bad - full resolution image loaded into memory
let image = UIImage(contentsOfFile: photoPath)
// 4032x3024 photo = ~48 MB in memory

// Good - downsample to display size
func downsample(imageAt url: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage? {
    let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
    let options: [CFString: Any] = [
        kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceShouldCacheImmediately: true,
        kCGImageSourceCreateThumbnailWithTransform: true,
        kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
    ]

    guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
          let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary)
    else { return nil }

    return UIImage(cgImage: cgImage)
}

Leaks Instrument

How Leaks Detection Works
  • Scans heap at intervals for objects with no root references

  • Detects unreachable memory - allocated but no path from stack/globals

  • Does NOT detect logical leaks (reachable but never used, like unbounded caches)

Common Retain Cycle Patterns
Closure Capturing Self
// Bad - retain cycle: self -> timer -> closure -> self
class ViewModel {
    var timer: Timer?

    func startPolling() {
        timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
            self.refresh() // Strong capture of self
        }
    }
}

// Good - weak capture
timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in
    self?.refresh()
}
Delegate Retain Cycle
// Bad - strong delegate creates cycle
protocol ServiceDelegate: AnyObject {
    func didComplete()
}

class Service {
    var delegate: ServiceDelegate? // Strong reference
}

class ViewModel: ServiceDelegate {
    let service = Service() // ViewModel -> Service -> ViewModel
    init() { service.delegate = self }
}

// Good - weak delegate
class Service {
    weak var delegate: ServiceDelegate?
}
Closure in Collection
// Bad - closures in array capture self strongly
class Coordinator {
    var handlers: [() -> Void] = []

    func register() {
        handlers.append {
            self.handleEvent() // Each closure retains self
        }
    }
}

// Good - weak capture in each closure
handlers.append { [weak self] in
    self?.handleEvent()
}
NotificationCenter (Pre-iOS 9 / Manual)
// Modern iOS/macOS: system auto-removes observers on dealloc
// But if using block-based API, the token retains the closure:

// Bad - token keeps closure alive
let token = NotificationCenter.default.addObserver(
    forName: .dataChanged, object: nil, queue: .main
) { _ in
    self.reload() // Retained by token
}

// Good - store and remove, or use weak self
let token = NotificationCenter.default.addObserver(
    forName: .dataChanged, object: nil, queue: .main
) { [weak self] _ in
    self?.reload()
}

Xcode Memory Graph Debugger

When to Use
  • Leaks instrument shows leaks but you need to see why objects are retained

  • You suspect retain cycles but can't find them in code review

  • You need to see the full ownership graph of an object

How to Use
  1. Run app in Debug mode (not Profile)

  2. Reproduce the state where objects should be deallocated

  3. Click the Memory Graph button in Xcode's debug bar (looks like interconnected nodes)

  4. Xcode pauses and captures the heap

Reading the Graph
  • Left sidebar: List of all live objects grouped by type

  • Purple exclamation marks: Xcode-detected leaks / retain cycles

  • Center canvas: Visual graph of object references

  • Click an object to see its retain graph - who holds a strong reference to it

Debugging Tips
  • Filter by your module name to ignore system objects

  • Look for cycles - two objects pointing at each other

  • Check backtrace in the right sidebar to see where the object was allocated

  • Export the graph: File > Export Memory Graph for sharing

Enable Malloc Stack Logging

For full allocation backtraces in Memory Graph Debugger:

  1. Scheme > Run > Diagnostics

  2. Enable Malloc Stack Logging (Live Allocations Only)

  3. Now the right sidebar shows the exact call stack that allocated each object

Autorelease Pool Optimization

In tight loops creating Objective-C bridged objects:

// Bad - autoreleased objects accumulate until loop ends
for item in largeDataSet {
    let string = item.name as NSString       // Autoreleased
    let data = string.data(using: .utf8)     // Autoreleased
    process(data)
}
// Memory spikes until loop completes and pool drains

// Good - drain pool each iteration
for item in largeDataSet {
    autoreleasepool {
        let string = item.name as NSString
        let data = string.data(using: .utf8)
        process(data)
    }
}
// Memory stays flat - pool drains each iteration
When autoreleasepool Matters
  • Processing large collections (1000+ items)

  • Creating temporary NSString, NSData, NSNumber objects in loops

  • Image processing pipelines

  • Not needed for pure Swift value types (String, Data, Array)

Memory Footprint Tracking in Code

import os

func logMemoryFootprint() {
    var info = mach_task_basic_info()
    var count = mach_msg_type_number_t(
        MemoryLayout<mach_task_basic_info>.size / MemoryLayout<natural_t>.size
    )
    let result = withUnsafeMutablePointer(to: &info) {
        $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
            task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
        }
    }
    if result == KERN_SUCCESS {
        let usedMB = Double(info.resident_size) / 1_048_576
        os_log("Memory footprint: %.1f MB", usedMB)
    }
}

Quick Diagnosis Checklist

  • [ ] Run Allocations with Generation Analysis - does memory grow across identical operations?

  • [ ] Run Leaks instrument - any detected leaks?

  • [ ] Check Memory Graph Debugger for retain cycles (purple warnings)

  • [ ] Search for self in closures without [weak self] or [unowned self]

  • [ ] Verify delegates are declared weak

  • [ ] Check NSCache usage instead of plain dictionaries for caches

  • [ ] Verify images are downsampled to display size

  • [ ] Use autoreleasepool in tight loops with ObjC-bridged objects

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Meng To
Publisher
Meng To (Community)
Source
MengTo/Skills · agent-skills/codex/performance-profiling · commit 5ea1661
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Meng To.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download performance-profiling.zip