Swift Performance Optimization Skill
Skill18 starsChanged 56 days agoMITView on GitHub
Use when investigating measured Swift or Apple-platform regressions in CPU, memory, launch, scrolling, animation hitches, image processing, energy, networking, or concurrency, or when designing performance tests and Instruments experiments. Do not use for speculative micro-optimization, ordinary refactoring, or a functional bug without performance evidence.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- termio-sh/termioword for word, first seen Aug 11, 2026
Other versions1 project uses a version of this.
Word for word · 1
- termio-sh/termio★ 787100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository14 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- app-intents-widgetsSkill
- Cross-Platform App Development SkillSkill
- iOS Accessibility SkillSkill
- iOS Animation Graphics SkillSkill
- iphone-duo-designSkill
- Memory Leak Diagnosis SkillSkill
- swift-concurrency-migrationSkill
- swiftdata-core-data-migrationsSkill
- Swift Modern Architecture SkillSkill
- SpeechAnalyzer Framework ExpertSkill
- SwiftUI Programming SkillSkill
- Swift Unit Testing SkillSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
16 rules. About 0 are common, 7 are distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈7
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 22
Add a regression threshold where the workload is stable enough to automate.
- Very specific: line 36
Use os_signpost or signposter intervals around important operations so traces answer product questions rather than only showing raw symbols.
- Very specific: line 41
Use weak when the owner may legitimately disappear before the callback.
- Very specific: line 42
Prefer structured async functions over storing completion closures.
- Very specific: line 44
Never use [unowned self] in a repeating timer merely to silence a cycle.
- Very specific: line 80
If a Foundation Timer is required, capture its owner weakly, store the timer, invalidate the old instance before starting another, and …
- Very specific: line 87
Keep UI state on @MainActor.
- Distinctive: line 88
Avoid spawning an unbounded task per item.
- Distinctive: line 89
Check cancellation before expensive phases and before publishing results.
- Distinctive: line 90
Do not trade actor safety for speed without race-focused tests and trace evidence.
- Distinctive: line 95
Avoid accidental copy-on-write churn in hot paths, but prove it with Allocations or profiling.
- Very specific: line 105
Keep work out of body: precompute formatting, filtering, decoding, and image processing at the correct layer.
- Very specific: line 107
Use .equatable()/EquatableView only after measurement, and include every visible input in equality.
- Very specific: line 108
Prefer .task(id:) for work tied to a view and input.
- Distinctive: line 118
Use a bounded cache whose cost reflects decoded pixels.
- Distinctive: line 127
Keep before/after traces with the scenario and build identifier.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Swift Performance Optimization Skill
Optimize from evidence. Preserve behavior, accessibility, data correctness, and lifecycle safety while changing performance characteristics.
Baseline
The copy-ready examples use Xcode 16, Swift 6 language mode with strict concurrency, and iOS 17. Most principles apply to older targets; verify each API against the app's actual minimum. Material from the OS 27 development cycle is beta relative to stable Xcode 26.6 and requires an explicit request, beta labeling, stable fallback, and availability gate.
Measurement workflow
- Define a user-visible symptom and a reproducible scenario.
- Record device, OS, build configuration, dataset, thermal state, and network conditions.
- Measure an optimized Release build on representative hardware. Simulator-only timing is not release evidence.
- Select the instrument that answers the hypothesis.
- Save a baseline trace or metric, change one variable, then repeat the same scenario.
- Confirm that the bottleneck moved and no memory, energy, correctness, or accessibility regression appeared.
- Add a regression threshold where the workload is stable enough to automate.
Useful tools include:
| Symptom | First evidence source |
| CPU-bound work | Time Profiler; inspect heavy stacks and self time |
| SwiftUI update cost | SwiftUI instrument plus Time Profiler |
| Scroll or animation stalls | Animation Hitches, Core Animation, signposts |
| Growth or leaks | Allocations, Leaks, Memory Graph, memgraphs |
| Slow launch | App Launch template and launch signposts |
| Battery or thermal issues | Energy Log and device testing |
| Field regressions | MetricKit payloads and app-specific telemetry |
Use os_signpost or signposter intervals around important operations so traces answer product questions rather than only showing raw symbols.
Lifetime and memory safety
- A capture is a cycle only when the closure is retained along a path back to its owner. Do not add
[weak self]mechanically to every closure. - Use
weakwhen the owner may legitimately disappear before the callback. Useunownedonly when the lifetime invariant is proven and documented; a wrong assumption traps. - Prefer structured
asyncfunctions over storing completion closures. - Cancel owned tasks and invalidate repeating timers when the owner stops needing them and during teardown.
- Never use
[unowned self]in a repeating timer merely to silence a cycle.
import Foundation
@MainActor
final class PollingModel {
private var task: Task<Void, Never>?
private(set) var tickCount = 0
func start() {
stop()
task = Task { [weak self] in
while !Task.isCancelled {
do {
try await Task.sleep(for: .seconds(1))
} catch {
return
}
guard let self else { return }
tickCount += 1
}
}
}
func stop() {
task?.cancel()
task = nil
}
deinit {
task?.cancel()
}
}If a Foundation Timer is required, capture its owner weakly, store the timer, invalidate the old instance before starting another, and invalidate it on stop/deinit.
See the lifecycle-safe example.
Concurrency
- Swift concurrency is the default for new asynchronous flows, but Dispatch and operation queues remain supported interoperability and scheduling tools.
- Keep UI state on
@MainActor. Move only verified expensive, concurrency-safe work away from it. - Avoid spawning an unbounded task per item. Use task groups with deliberate limits, an actor, an async sequence, or a bounded worker design.
- Check cancellation before expensive phases and before publishing results.
- Do not trade actor safety for speed without race-focused tests and trace evidence.
Collections and computation
- Pick structures by operation: a
Setor dictionary can replace repeated linear membership searches. - Avoid accidental copy-on-write churn in hot paths, but prove it with Allocations or profiling.
- Reserve capacity only when the final scale is reasonably known.
- Cache only expensive, repeatable results with a clear invalidation rule and a bounded memory policy.
- Benchmark optimized code with representative data; debug-build microbenchmarks are misleading.
SwiftUI
- Stable identity is mandatory for mutable collections. Prefer model IDs, not offsets or a new UUID computed during rendering.
Listalready realizes rows lazily.ScrollViewplusLazyVStackoffers different styling and interaction behavior; it is not inherently faster.- A
bodyevaluation is value computation, not proof that all descendants were redrawn. Use the SwiftUI instrument to identify expensive updates. - Keep work out of
body: precompute formatting, filtering, decoding, and image processing at the correct layer. - Extract views for responsibility and data-flow clarity. Do not claim extraction alone establishes an isolated rendering boundary.
- Use
.equatable()/EquatableViewonly after measurement, and include every visible input in equality. - Prefer
.task(id:)for work tied to a view and input. It cancels prior work when the ID changes.
See the list identity example.
Images and reusable cells
- Decode and downsample to the rendered pixel size rather than decoding full-resolution assets for thumbnails.
- Validate HTTP responses, cancel obsolete requests, and check both cancellation and represented URL before assigning an image.
- Reset image, identity, and task in
prepareForReuse(). - Lay out with constraints or
layoutSubviews; a one-time frame set during initialization will not follow cell resizing. - Use a bounded cache whose cost reflects decoded pixels. Add collection-view prefetching only after measuring its value and cancel prefetches when appropriate.
- Register cell classes/nibs, implement item counts, and avoid force-casting dequeued cells in copy-ready examples.
See the complete downsampling and reuse example.
Shipping checks
- Compare percentile metrics, not only averages.
- Set thresholds that account for device classes and natural variance.
- Keep before/after traces with the scenario and build identifier.
- Re-test memory warnings, background/foreground transitions, cancellation, large accessibility text, and low-power/thermal conditions.
- State what was not measured; never market an optimization as proven from code inspection alone.
Resources
- List performance example
- Task lifetime example
- Image downsampling and cell reuse
- Performance investigation prompts
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

