Skip to content

Swift Performance Optimization

Language-level performance patterns for memory efficiency, runtime speed, and zero-cost abstractions. Profile first, optimize later — use this skill after Instruments identifies Swift code as the bottleneck.

When to Use

Use this skill when:

  • Time Profiler shows Swift code as hotspot
  • Excessive memory allocations or retain/release traffic
  • Implementing performance-critical algorithms
  • Writing framework code with performance requirements
  • Optimizing tight loops or frequently called methods

Do NOT use for

  • First-step optimization (use performance-profiling first)
  • SwiftUI performance (use swiftui-performance)
  • Premature optimization

Example Prompts

  • "Profiler shows excessive copying — how do I eliminate it?"
  • "Retain/release overhead in Time Profiler — how to reduce?"
  • "Generic code is slow in hot path"
  • "Actor overhead causing UI jank"

What This Skill Provides

Four Principles of Swift Performance

From WWDC 2024-10217 — the organizing mental model for all optimizations:

  1. Function Calls – Static vs dynamic dispatch, generic specialization
  2. Memory Allocation – Stack vs heap, when each occurs
  3. Memory Layout – Contiguous vs pointer-chasing, cache lines
  4. Value Copying – COW triggers, defensive copies, ARC traffic

Core Topics

  1. Noncopyable Types – Swift 6 ~Copyable for types that should never be copied
  2. Copy-on-Write – Use isKnownUniquelyReferenced(), reserveCapacity(), and avoid defensive copies
  3. Value vs Reference – Structs under 64 bytes are fast; larger need indirect storage
  4. ARC Optimizationunowned is ~2x faster than weak; closure capture costs (escaping vs non-escaping)
  5. Generics – Use some over any for static dispatch
  6. Collection PerformanceContiguousArray is ~15% faster than Array; InlineArray for fixed sizes
  7. Concurrency – Actor hops cost ~100μs; batch calls
  8. Memory Layout – Struct padding, exclusivity checks, cache-friendly data structures
  9. Span Types – Safe zero-copy memory access with OutputSpan for initialization

Each topic ships with before/after code patterns, measured costs, and a code-review checklist — those live in the skill itself.

Resources

WWDC: 2025-312, 2024-10217, 2024-10170, 2021-10216, 2016-416

Released under the MIT License