Use when app feels slow, memory grows over time, battery drains fast, or you want to profile proactively - decision trees to choose the right Instruments tool, deep workflows for Time Profiler/Allocations/Core Data, and pressure scenarios for misinterpreting results
iOS app performance problems fall into distinct categories, each with a specific diagnosis tool. This skill helps you choose the right tool, use it effectively, and interpret results correctly under pressure.
Core principle: Measure before optimizing. Guessing about performance wastes more time than profiling.
Requires: Xcode 15+, iOS 14+
Related skills: axiom-swiftui-performance (SwiftUI-specific profiling with Instruments 26), axiom-memory-debugging (memory leak diagnosis)
axiom-memory-debugging instead whenaxiom-swiftui-performance instead whenBefore opening Instruments, narrow down what you're actually investigating.
App performance problem?
├─ App feels slow or lags (UI interactions stall, scrolling stutters)
│ └─ → Use Time Profiler (measure CPU usage)
├─ Memory grows over time (Xcode shows increasing memory)
│ └─ → Use Allocations (measure object creation)
├─ Data loading is slow (parsing, database queries, API calls)
│ └─ → Use Core Data instrument (if using Core Data)
│ └─ → Use Time Profiler (if it's computation)
└─ Battery drains fast (device gets hot, depletes in hours)
└─ → Use Energy Impact (measure power consumption)
YES – Use Instruments to measure it (profiling is most accurate)
NO – Use profiling proactively
Time Profiler – Slowness, UI lag, CPU spikes Allocations – Memory growth, memory pressure, object counts Core Data – Query performance, fetch times, fault fires Energy Impact – Battery drain, sustained power draw Network Link Conditioner – Connection-related slowness System Trace – Thread blocking, main thread blocking, scheduling
Use Time Profiler when your app feels slow or laggy. It measures CPU time spent in each function.
open -a Instruments
Select "Time Profiler" template.
The top panel shows a timeline of CPU usage over time. Look for:
In the call tree, click "Heaviest Stack Trace" to see which functions use the most CPU:
Time Profiler Results
MyViewController.viewDidLoad() – 500ms (40% of total)
├─ DataParser.parse() – 350ms
│ └─ JSONDecoder.decode() – 320ms
└─ UITableView.reloadData() – 150ms
Self Time = Time spent IN that function (not in functions it calls) Total Time = Time spent in that function + everything it calls
// ❌ WRONG: Profile shows DataParser.parse() is 80% CPU
// Conclusion: "DataParser is slow, let me optimize it"
// ✅ RIGHT: Check what DataParser is calling
// If JSONDecoder.decode() is doing 99% of the work,
// optimize JSON decoding, not DataParser
The issue: A function with high Total Time might be calling slow code, not doing slow work itself.
Fix: Look at Self Time, not Total Time. Drill down to see what each function calls.
// ❌ WRONG: Profile app in Simulator
// Simulator CPU is different than real device
// Results don't reflect actual device performance
// ✅ RIGHT: Profile on actual device
// Device settings: Developer Mode enabled, Xcode attached
Fix: Always profile on actual device for accurate CPU measurements.
// ❌ WRONG: Profile entire app startup
// Sees 2000ms startup time, many functions involved
// ✅ RIGHT: Profile just the slow part
// "App feels slow when scrolling" → profile only scrolling
// Separate concerns: startup slow vs interaction slow
Fix: Reproduce the specific slow operation, not the entire app.
The temptation: "I must optimize function X!"
The reality: Function X might be:
What to do instead:
Check Self Time, not Total Time
Drill down one level
Check the timeline
Ask: Will users notice?
Time cost: 5 min (read results) + 2 min (drill down) = 7 minutes to understand
Cost of guessing: 2 hours optimizing wrong function + 1 hour realizing it didn't help + back to square one = 3+ hours wasted
Use Allocations when memory grows over time or you suspect memory pressure issues.
open -a Instruments
Select "Allocations" template.
Look at the main chart:
Under "Statistics":
UIImage: 500 instances (300MB) – Should be <50 for normal app
NSString: 50000 instances – Should be <1000
CustomDataModel: 10000 instances – Should be <100
// ❌ WRONG: Memory went from 100MB to 500MB
// Conclusion: "There's a leak, memory keeps growing!"
// ✅ RIGHT: Check what caused the growth
// Loaded 1000 images (normal)
// Cached API responses (normal)
// User has 5000 contacts (normal)
// Memory is being used correctly
The issue: Growing memory ≠ leak. Apps legitimately use more memory when loading data.
Fix: Check Allocations for object counts. If images/data count matches what you loaded, it's normal. If object count keeps growing without actions, that's a leak.
// ❌ WRONG: Allocations shows 1000 UIImages in memory
// Conclusion: "Memory leak, too many images!"
// ✅ RIGHT: Check if this is intentional caching
// ImageCache holds up to 1000 images by design
// When memory pressure happens, cache is cleared
// Normal behavior
Fix: Distinguish between intended caching and actual leaks. Leaks don't release under memory pressure.
// ❌ WRONG: Record for 5 seconds, see 200MB
// Conclusion: "App uses 200MB, optimize memory"
// ✅ RIGHT: Record for 2-3 minutes, see full lifecycle
// Load data: 200MB
// Navigate away: 180MB (20MB still cached)
// Navigate back: 190MB (cache reused)
// Real baseline: ~190MB at steady state
Fix: Profile long enough to see memory stabilize. Short recordings capture transient spikes.
The temptation: "Delete caching, reduce object creation, optimize data structures"
The reality: Is 500MB actually large?
What to do instead:
Establish baseline on real device
# On device, open Memory view in Xcode
Xcode → Debug → Memory Debugger → Check "Real Memory" at app launch
Check object counts, not total memory
Test under memory pressure
Profile real user journey
Time cost: 5 min (launch Allocations) + 3 min (record app usage) + 2 min (analyze) = 10 minutes
Cost of guessing: Delete caching to "reduce memory" → app reloads data every screen → slower app → users complain → revert changes = 2+ hours wasted
Use Core Data instrument when your app uses Core Data and data loading is slow.
Add to your launch arguments in Xcode:
Edit Scheme → Run → Arguments Passed On Launch
Add: -com.apple.CoreData.SQLDebug 1
Now SQLite queries print to console:
CoreData: sql: SELECT ... FROM tracks WHERE artist = ? (time: 0.015s)
CoreData: sql: SELECT ... FROM albums WHERE id = ? (time: 0.002s)
Watch the console during a typical user action (load list, scroll, filter):
❌ BAD: Loading 100 tracks, then querying album for each
SELECT * FROM tracks (time: 0.050s) → 100 tracks
SELECT * FROM albums WHERE id = 1 (time: 0.005s)
SELECT * FROM albums WHERE id = 2 (time: 0.005s)
SELECT * FROM albums WHERE id = 3 (time: 0.005s)
... 97 more queries
Total: 0.050s + (100 × 0.005s) = 0.550s
✅ GOOD: Fetch tracks WITH album relationship (eager loading)
SELECT tracks.*, albums.* FROM tracks
LEFT JOIN albums ON tracks.albumId = albums.id
(time: 0.050s)
Total: 0.050s
open -a Instruments
Select "Core Data" template.
Record while performing slow action:
Core Data Results
Fetch Requests: 102
Average Fetch Time: 12ms
Slow Fetch: "SELECT * FROM tracks" (180ms)
Fault Fires: 5000
→ Object accessed, requires fetch from database
→ Should use prefetching
// ❌ WRONG: Fetch tracks, then access album for each
let tracks = try context.fetch(Track.fetchRequest())
for track in tracks {
print(track.album.title) // Fires individual query for each
}
// Total: 1 + N queries
// ✅ RIGHT: Fetch with relationship prefetching
let request = Track.fetchRequest()
request.returnsObjectsAsFaults = false
request.relationshipKeyPathsForPrefetching = ["album"]
let tracks = try context.fetch(request)
for track in tracks {
print(track.album.title) // Already loaded
}
// Total: 1 query
Fix: Use relationshipKeyPathsForPrefetching to load related objects upfront.
// ❌ WRONG: Fetch 50,000 records all at once
let request = Track.fetchRequest()
let allTracks = try context.fetch(request) // Huge memory spike
// ✅ RIGHT: Batch fetch in chunks
let request = Track.fetchRequest()
request.fetchBatchSize = 500 // Fetch 500 at a time
let allTracks = try context.fetch(request) // Memory efficient
Fix: Use fetchBatchSize for large datasets.
// ❌ WRONG: Keep all objects in memory
let request = Track.fetchRequest()
request.returnsObjectsAsFaults = false // Keep all in memory
let allTracks = try context.fetch(request) // 50,000 objects
// Memory spike if you don't use all of them
// ✅ RIGHT: Use faults (lazy loading)
let request = Track.fetchRequest()
// request.returnsObjectsAsFaults = true (default)
let allTracks = try context.fetch(request) // Just references
// Only load objects you actually access
Fix: Leave returnsObjectsAsFaults as default (true) unless you need all objects upfront.
The temptation: "The schema is wrong, I need to restructure everything"
The reality: 99% of "slow Core Data" is due to:
Redesigning the schema is the LAST thing to try.
What to do instead:
Enable SQL debugging (2 min)
-com.apple.CoreData.SQLDebug 1 launch argumentLook for N+1 pattern (3 min)
Add indexes if needed (5 min)
@NSManaged var artist: String with frequent filtering?@Index in schemaTest improvement (2 min)
Only THEN consider schema changes (30+ min)
Time cost: 12 minutes to diagnose + fix = 12 minutes
Cost of schema redesign: 8 hours design + 4 hours migration + 2 hours testing + 1 hour rollback = 15 hours total
When to use: App drains battery fast, device gets hot
Workflow:
Key metrics:
Common issues:
When to use: App seems slow on 4G, want to test without traveling
Setup:
Key profiles:
Note: Also covered in ui-testing for network-dependent test scenarios.
When to use: UI freezes or is janky, but Time Profiler shows low CPU
Common cause: Main thread blocked by background task waiting on lock
Workflow:
Key metrics:
While Time Profiler shows where CPU time goes generally, OSSignposter lets you measure specific operations you define. It's the primary tool for custom performance instrumentation on Apple platforms.
import os
let signposter = OSSignposter(subsystem: "com.app", category: "DataLoad")
// Interval measurement (start → end)
func loadData() async throws -> [Item] {
let signpostID = signposter.makeSignpostID()
let state = signposter.beginInterval("Load Items", id: signpostID)
defer { signposter.endInterval("Load Items", state) }
return try await fetchItems()
}
// Point of interest (single event)
func cacheHit(for key: String) {
signposter.emitEvent("Cache Hit")
}
| Need | Tool | |------|------| | General CPU hotspots | Time Profiler | | Specific operation duration | OSSignposter | | Cross-thread operation timing | OSSignposter | | Automated regression testing | OSSignposter + XCTOSSignpostMetric |
The problem: You run Time Profiler 3 times, get 200ms, 150ms, 280ms. Which is correct?
Red flags you might think:
The reality: Variance is NORMAL. Different runs hit different:
What to do instead:
Warm up the cache (first run always slower)
Control system load
Look for the pattern
Trust the slowest run (worst case scenario)
Time cost: 10 min (run profiler 3x) + 2 min (interpret) = 12 minutes
Cost of ignoring variance: Miss intermittent performance issue → users see occasional freezes → bad reviews
The problem: Time Profiler shows JSON parsing is slow. Allocations show memory use is normal. Which to fix?
The answer: Both are real, prioritize differently.
Time Profiler: JSONDecoder.decode() = 500ms
Allocations: Memory = 250MB (normal for app size)
Result: App is slow AND memory is fine
Action: Optimize JSON decoding (not memory)
Common conflicts:
| Time Profiler | Allocations | Action | |---|---|---| | High CPU | Normal memory | Optimize computation (reduce CPU) | | Low CPU | Memory growing | Find leak or reduce object creation | | Both high | Both high | Profile which is user-visible first |
What to do:
Prioritize by user impact
Check if they're related
Fix in order of impact
Time cost: 5 min (analyze both results) = 5 minutes
Cost of fixing wrong problem: Spend 4 hours optimizing memory that's fine → no improvement to user experience
The situation: Manager says "We ship in 2 hours. Is performance acceptable?"
Red flags you might think:
The reality: Profiling takes 15-20 minutes total. That's 1% of your remaining time.
What to do instead:
Profile the critical path (3 min)
Record one proper run (5 min)
Interpret quickly (5 min)
Ship with confidence (2 min)
Time cost: 15 min profiling + 5 min analysis = 20 minutes
Cost of not profiling: Ship with unknown performance → Users hit slowness → Bad reviews → Emergency hotfix 2 weeks later
Math: 20 minutes of profiling now << 2+ weeks of post-launch support
// Time Profiler: Launch Instruments
open -a Instruments
// Core Data: Enable SQL logging
// Edit Scheme → Run → Arguments Passed On Launch
-com.apple.CoreData.SQLDebug 1
// Allocations: Check persistent objects
Instruments → Allocations → Statistics → sort "Persistent"
// Memory warning: Simulate pressure
Xcode → Debug → Simulate Memory Warning
// Energy Impact: Profile battery drain
Instruments → Energy Impact template
// Network Link Conditioner: Simulate 3G
System Preferences → Network Link Conditioner → 3G profile
Performance problem?
├─ App feels slow/laggy?
│ └─ → Time Profiler (measure CPU)
├─ Memory grows over time?
│ └─ → Allocations (find object growth)
├─ Data loading is slow?
│ └─ → Core Data instrument (if using Core Data)
│ └─ → Time Profiler (if computation slow)
└─ Battery drains fast?
└─ → Energy Impact (measure power)
*Scenario
<!-- Content truncated for initial SEO render. Open the source file tab for the full file. -->npx skills add megastep/axiom-performance-profiling下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer