[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6E6Q4VMZAKR2ZACERAVNF68":3,"skill-same:01M6E6Q4VMZAKR2ZACERAVNF68":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":29,"linkOnly":30,"markdownContent":31,"markdownBody":32,"frontMatter":33,"refName":36,"commitSha":37,"skillDirectory":38,"forksCount":39,"repositoryHtmlUrl":40,"repositoryHomepageUrl":41,"ownerHtmlUrl":42,"ownerBlogUrl":6,"ownerDescription":43,"updatedAt":44,"install":45,"resources":58},"01M6E6Q4VMZAKR2ZACERAVNF68","axiom-swift-performance",null,"Use when optimizing Swift code performance, reducing memory usage, improving runtime efficiency, dealing with COW, ARC overhead, generics specialization, or collection optimization","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-swift-performance\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28],"swift","performance","axiom swift performance","memory","code","Optimization","collection","use","efficiency","runtime","2026-11-10 10:12:30",false,"---\nname: axiom-swift-performance\ndescription: Use when optimizing Swift code performance, reducing memory usage, improving runtime efficiency, dealing with COW, ARC overhead, generics specialization, or collection optimization\nlicense: MIT\nmetadata:\n  version: \"1.2.0\"\n---\n\n# Swift Performance Optimization\n\n## Purpose\n\n**Core Principle**: Optimize Swift code by understanding language-level performance characteristics—value semantics, ARC behavior, generic specialization, and memory layout—to write fast, efficient code without premature micro-optimization.\n\n**Swift Version**: Swift 6.2+ (for InlineArray, Span, `@concurrent`)\n**Xcode**: 16+\n**Platforms**: iOS 18+, macOS 15+\n\n**Related Skills**:\n- `axiom-performance-profiling` — Use Instruments to measure (do this first!)\n- `axiom-swiftui-performance` — SwiftUI-specific optimizations\n- `axiom-build-performance` — Compilation speed\n- `axiom-swift-concurrency` — Correctness-focused concurrency patterns\n\n## When to Use This Skill\n\n### ✅ Use this skill when\n\n- App profiling shows Swift code as the bottleneck (Time Profiler hotspots)\n- Excessive memory allocations or retain\u002Frelease traffic\n- Implementing performance-critical algorithms or data structures\n- Writing framework or library code with performance requirements\n- Optimizing tight loops or frequently called methods\n- Dealing with large data structures or collections\n- Code review identifying performance anti-patterns\n\n## Quick Decision Tree\n\n```\nPerformance issue identified?\n│\n├─ Profiler shows excessive copying?\n│  └─ → Part 1: Noncopyable Types\n│  └─ → Part 2: Copy-on-Write\n│\n├─ Retain\u002Frelease overhead in Time Profiler?\n│  └─ → Part 4: ARC Optimization\n│\n├─ Generic code in hot path?\n│  └─ → Part 5: Generics & Specialization\n│\n├─ Collection operations slow?\n│  └─ → Part 7: Collection Performance\n│\n├─ Async\u002Fawait overhead visible?\n│  └─ → Part 8: Concurrency Performance\n│\n├─ Struct vs class decision?\n│  └─ → Part 3: Value vs Reference\n│\n└─ Memory layout concerns?\n   └─ → Part 9: Memory Layout\n```\n\n---\n\n## The Four Principles of Swift Performance\n\nFrom WWDC 2024-10217: Swift's low-level performance characteristics come down to four areas. Each maps to a Part in this skill.\n\n| Principle | What It Costs | Skill Coverage |\n|-----------|--------------|----------------|\n| **Function Calls** | Dispatch overhead, optimization barriers | Part 5 (Generics), Part 6 (Inlining) |\n| **Memory Allocation** | Stack vs heap, allocation frequency | Part 3 (Value vs Reference), Part 7 (Collections) |\n| **Memory Layout** | Cache locality, padding, contiguity | Part 9 (Memory Layout), Part 11 (Span) |\n| **Value Copying** | COW triggers, defensive copies, ARC traffic | Part 1 (Noncopyable), Part 2 (COW), Part 4 (ARC) |\n\nUnderstanding which principle is causing your bottleneck determines which Part to use.\n\n---\n\n## Part 1: Noncopyable Types (~Copyable)\n\n**Swift 6.0+** introduces noncopyable types for performance-critical scenarios where you want to avoid implicit copies.\n\n### When to Use\n\n- Large types that should never be copied (file handles, GPU buffers)\n- Types with ownership semantics (must be explicitly consumed)\n- Performance-critical code where copies are expensive\n\n### Basic Pattern\n\n```swift\n\u002F\u002F Noncopyable type\nstruct FileHandle: ~Copyable {\n    private let fd: Int32\n\n    init(path: String) throws {\n        self.fd = open(path, O_RDONLY)\n        guard fd != -1 else { throw FileError.openFailed }\n    }\n\n    deinit {\n        close(fd)\n    }\n\n    \u002F\u002F Must explicitly consume\n    consuming func close() {\n        _ = consume self\n    }\n}\n\n\u002F\u002F Usage\nfunc processFile() throws {\n    let handle = try FileHandle(path: \"\u002Fdata.txt\")\n    \u002F\u002F handle is automatically consumed at end of scope\n    \u002F\u002F Cannot accidentally copy handle\n}\n```\n\n### Ownership Annotations\n\n```swift\n\u002F\u002F consuming - takes ownership, caller cannot use after\nfunc process(consuming data: [UInt8]) {\n    \u002F\u002F data is consumed\n}\n\n\u002F\u002F borrowing - temporary access without ownership\nfunc validate(borrowing data: [UInt8]) -> Bool {\n    \u002F\u002F data can still be used by caller\n    return data.count > 0\n}\n\n\u002F\u002F inout - mutable access\nfunc modify(inout data: [UInt8]) {\n    data.append(0)\n}\n```\n\n### Performance Impact\n\n- **Eliminates implicit copies**: Compiler error instead of runtime copy\n- **Zero-cost abstraction**: Same performance as manual memory management\n- **Use when**: Type is expensive to copy (>64 bytes) and copies are rare\n\n---\n\n## Part 2: Copy-on-Write (COW)\n\nSwift collections use COW for efficient memory sharing. Understanding when copies happen is critical for performance.\n\n### How COW Works\n\n```swift\nvar array1 = [1, 2, 3]  \u002F\u002F Single allocation\nvar array2 = array1     \u002F\u002F Share storage (no copy)\narray2.append(4)        \u002F\u002F Now copies (array1 modified array2)\n```\n\nFor custom COW implementation, see Copy-Paste Pattern 1 (COW Wrapper) below.\n\n### Performance Tips\n\n```swift\n\u002F\u002F ❌ Accidental copy in loop\nfor i in 0..\u003Carray.count {\n    array[i] = transform(array[i])  \u002F\u002F Copy on first mutation if shared!\n}\n\n\u002F\u002F ✅ Reserve capacity first (ensures unique)\narray.reserveCapacity(array.count)\nfor i in 0..\u003Carray.count {\n    array[i] = transform(array[i])\n}\n\n\u002F\u002F ❌ Multiple mutations trigger multiple uniqueness checks\narray.append(1)\narray.append(2)\narray.append(3)\n\n\u002F\u002F ✅ Single reservation\narray.reserveCapacity(array.count + 3)\narray.append(contentsOf: [1, 2, 3])\n```\n\n### Defensive Copies\n\nFrom WWDC 2024-10217: Swift sometimes inserts *defensive copies* when it cannot prove a value won't be mutated through a shared reference.\n\n```swift\nclass DataStore {\n    var items: [Item] = []  \u002F\u002F COW type stored in class\n}\n\nfunc process(_ store: DataStore) {\n    for item in store.items {\n        \u002F\u002F Swift may defensively copy `items` because:\n        \u002F\u002F 1. store.items is a class property (another reference could mutate it)\n        \u002F\u002F 2. The loop needs a stable snapshot\n        handle(item)\n    }\n}\n```\n\n**How to avoid**: Copy to a local variable first — one explicit copy instead of repeated defensive copies:\n\n```swift\nfunc process(_ store: DataStore) {\n    let items = store.items  \u002F\u002F One copy\n    for item in items {\n        handle(item)  \u002F\u002F No more defensive copies\n    }\n}\n```\n\n**In profiler**: Defensive copies appear as unexpected `swift_retain`\u002F`swift_release` pairs or `Array.__allocating_init` calls when you didn't expect allocation.\n\n---\n\n## Part 3: Value vs Reference Semantics\n\nChoosing between `struct` and `class` has significant performance implications.\n\n### Decision Matrix\n\n| Factor | Use Struct | Use Class |\n|--------|-----------|-----------|\n| **Size** | ≤ 64 bytes | > 64 bytes or contains large data |\n| **Identity** | No identity needed | Needs identity (===) |\n| **Inheritance** | Not needed | Inheritance required |\n| **Mutation** | Infrequent | Frequent in-place updates |\n| **Sharing** | No sharing needed | Must be shared across scope |\n\n### Small Structs (Fast)\n\n```swift\n\u002F\u002F ✅ Fast - fits in registers, no heap allocation\nstruct Point {\n    var x: Double  \u002F\u002F 8 bytes\n    var y: Double  \u002F\u002F 8 bytes\n}  \u002F\u002F Total: 16 bytes - excellent for struct\n\nstruct Color {\n    var r, g, b, a: UInt8  \u002F\u002F 4 bytes total - perfect for struct\n}\n```\n\n### Large Structs (Slow)\n\n```swift\n\u002F\u002F ❌ Slow - excessive copying\nstruct HugeData {\n    var buffer: [UInt8]  \u002F\u002F 1MB\n    var metadata: String\n}\n\nfunc process(_ data: HugeData) {  \u002F\u002F Copies 1MB!\n    \u002F\u002F ...\n}\n\n\u002F\u002F ✅ Use reference semantics for large data\nfinal class HugeData {\n    var buffer: [UInt8]\n    var metadata: String\n}\n\nfunc process(_ data: HugeData) {  \u002F\u002F Only copies pointer (8 bytes)\n    \u002F\u002F ...\n}\n```\n\n### Indirect Storage for Flexibility\n\nFor large data that needs value semantics externally with reference storage internally, use the COW Wrapper pattern — see Copy-Paste Pattern 1 below.\n\n---\n\n## Part 4: ARC Optimization\n\nAutomatic Reference Counting adds overhead. Minimize it where possible.\n\n### Weak vs Unowned Performance\n\n```swift\nclass Parent {\n    var child: Child?\n}\n\nclass Child {\n    \u002F\u002F ❌ Weak adds overhead (optional, thread-safe zeroing)\n    weak var parent: Parent?\n}\n\n\u002F\u002F ✅ Unowned when you know lifetime guarantees\nclass Child {\n    unowned let parent: Parent  \u002F\u002F No overhead, crashes if parent deallocated\n}\n```\n\n**Performance**: `unowned` is ~2x faster than `weak` (no atomic operations).\n\n**Use when**: Child lifetime \u003C Parent lifetime (guaranteed).\n\n### Closure Capture Optimization\n\n```swift\nclass DataProcessor {\n    var data: [Int]\n\n    \u002F\u002F ❌ Captures self strongly, then uses weak - unnecessary weak overhead\n    func process(completion: @escaping () -> Void) {\n        DispatchQueue.global().async { [weak self] in\n            guard let self else { return }\n            self.data.forEach { print($0) }\n            completion()\n        }\n    }\n\n    \u002F\u002F ✅ Capture only what you need\n    func process(completion: @escaping () -> Void) {\n        let data = self.data  \u002F\u002F Copy value type\n        DispatchQueue.global().async {\n            data.forEach { print($0) }  \u002F\u002F No self captured\n            completion()\n        }\n    }\n}\n```\n\n### Closure Capture Costs\n\nFrom WWDC 2024-10217: Closures have different performance profiles depending on whether they escape.\n\n```swift\n\u002F\u002F Non-escaping closure — stack-allocated context, zero ARC overhead\nfunc processItems(_ items: [Item], using transform: (Item) -> Result) -> [Result] {\n    items.map(transform)  \u002F\u002F Closure context lives on stack\n}\n\n\u002F\u002F Escaping closure — heap-allocated context, ARC on every captured reference\nfunc processItemsLater(_ items: [Item], transform: @escaping (Item) -> Result) {\n    \u002F\u002F Closure context heap-allocated as anonymous class instance\n    \u002F\u002F Each captured reference gets retain\u002Frelease\n    self.pending = { items.map(transform) }\n}\n```\n\n**Why this matters**: `@Sendable` closures are always escaping, meaning every Task closure heap-allocates its capture context.\n\n**In hot paths**: Prefer non-escaping closures. If you see `swift_allocObject` in Time Profiler for closure contexts, look for escaping closures that could be non-escaping.\n\n### Observable Object Lifetimes\n\n**From WWDC 2021-10216**: Object lifetimes end at **last use**, not at closing brace.\n\n```swift\n\u002F\u002F ❌ Relying on observed lifetime is fragile\nclass Traveler {\n    weak var account: Account?\n\n    deinit {\n        print(\"Deinitialized\")  \u002F\u002F May run BEFORE expected with ARC optimizations!\n    }\n}\n\nfunc test() {\n    let traveler = Traveler()\n    let account = Account(traveler: traveler)\n    \u002F\u002F traveler's last use is above - may deallocate here!\n    account.printSummary()  \u002F\u002F weak reference may be nil!\n}\n\n\u002F\u002F ✅ Explicitly extend lifetime when needed\nfunc test() {\n    let traveler = Traveler()\n    let account = Account(traveler: traveler)\n\n    withExtendedLifetime(traveler) {\n        account.printSummary()  \u002F\u002F traveler guaranteed to live\n    }\n}\n```\n\nObject lifetimes can change between Xcode versions, Debug vs Release, and unrelated code changes. Enable \"Optimize Object Lifetimes\" (Xcode 13+) during development to expose hidden lifetime bugs early.\n\n---\n\n## Part 5: Generics & Specialization\n\nGeneric code can be fast or slow depending on specialization.\n\n### Specialization Basics\n\n```swift\n\u002F\u002F Generic function\nfunc process\u003CT>(_ value: T) {\n    print(value)\n}\n\n\u002F\u002F Calling with concrete type\nprocess(42)  \u002F\u002F Compiler specializes: process_Int(42)\nprocess(\"hello\")  \u002F\u002F Compiler specializes: process_String(\"hello\")\n```\n\n### Existential Overhead\n\n```swift\nprotocol Drawable {\n    func draw()\n}\n\n\u002F\u002F ❌ Existential container - expensive (heap allocation, indirection)\nfunc drawAll(shapes: [any Drawable]) {\n    for shape in shapes {\n        shape.draw()  \u002F\u002F Dynamic dispatch through witness table\n    }\n}\n\n\u002F\u002F ✅ Generic with constraint - can specialize\nfunc drawAll\u003CT: Drawable>(shapes: [T]) {\n    for shape in shapes {\n        shape.draw()  \u002F\u002F Static dispatch after specialization\n    }\n}\n```\n\n**Performance**: Generic version ~10x faster (eliminates witness table overhead).\n\n### Existential Container Overhead\n\n**From WWDC 2016-416**: `any Protocol` uses a 40-byte existential container (5 words on 64-bit). The container stores type metadata + protocol witness table (16 bytes) plus a 24-byte inline value buffer. Types ≤24 bytes are stored directly in the buffer (fast, ~5ns access); larger types require a heap allocation with pointer indirection (slower, ~15ns). `some Protocol` eliminates all container overhead (~2ns).\n\n**When `some` isn't available** (heterogeneous collections require `any`):\n- **Reduce type sizes to ≤24 bytes** — keep protocol-conforming types small enough for inline storage (3 words: e.g., `Point { x, y, z: Double }` fits exactly)\n- **Use enum dispatch instead** — eliminates containers entirely, trades open extensibility for performance:\n\n```swift\n\u002F\u002F ❌ Existential: 40 bytes\u002Felement, witness table dispatch\nlet shapes: [any Drawable] = [circle, rect]\n\n\u002F\u002F ✅ Enum: value-sized, static dispatch via switch\nenum Shape { case circle(Circle), rect(Rect) }\nfunc draw(_ shape: Shape) {\n    switch shape {\n    case .circle(let c): c.draw()\n    case .rect(let r): r.draw()\n    }\n}\n```\n\n- **Batch operations** — amortize per-element existential overhead by processing in chunks rather than one-at-a-time\n- **Measure first** — existential overhead (~10ns\u002Faccess) only matters in tight loops; for UI-level code it's negligible\n\n### `@_specialize` Attribute\n\nForce specialization for common types when the compiler doesn't do it automatically:\n\n```swift\n@_specialize(where T == Int)\n@_specialize(where T == String)\nfunc process\u003CT: Comparable>(_ value: T) -> T { value }\n\u002F\u002F Generates specialized versions + generic fallback\n```\n\n---\n\n## Part 6: Inlining\n\nInlining eliminates function call overhead but increases code size.\n\n### When to Inline\n\n```swift\n\u002F\u002F ✅ Small, frequently called functions\n@inlinable\npublic func fastAdd(_ a: Int, _ b: Int) -> Int {\n    return a + b\n}\n\n\u002F\u002F ❌ Large functions - code bloat\n@inlinable  \u002F\u002F Don't do this!\npublic func complexAlgorithm() {\n    \u002F\u002F 100 lines of code...\n}\n```\n\n### Cross-Module Optimization\n\n```swift\n\u002F\u002F Framework code\npublic struct Point {\n    public var x: Double\n    public var y: Double\n\n    \u002F\u002F ✅ Inlinable for cross-module optimization\n    @inlinable\n    public func distance(to other: Point) -> Double {\n        let dx = x - other.x\n        let dy = y - other.y\n        return sqrt(dx*dx + dy*dy)\n    }\n}\n\n\u002F\u002F Client code\nlet p1 = Point(x: 0, y: 0)\nlet p2 = Point(x: 3, y: 4)\nlet d = p1.distance(to: p2)  \u002F\u002F Inlined across module boundary\n```\n\n### `@usableFromInline`\n\n```swift\n\u002F\u002F Internal helper that can be inlined\n@usableFromInline\ninternal func helperFunction() { }\n\n\u002F\u002F Public API that uses it\n@inlinable\npublic func publicAPI() {\n    helperFunction()  \u002F\u002F Can inline internal function\n}\n```\n\n**Trade-off**: `@inlinable` exposes implementation, prevents future optimization.\n\n---\n\n## Part 7: Collection Performance\n\nChoosing the right collection and using it correctly matters.\n\n### Array vs ContiguousArray\n\n```swift\n\u002F\u002F ❌ Array\u003CT> - may use NSArray bridging (Swift\u002FObjC interop)\nlet array: Array\u003CInt> = [1, 2, 3]\n\n\u002F\u002F ✅ ContiguousArray\u003CT> - guaranteed contiguous memory (no bridging)\nlet array: ContiguousArray\u003CInt> = [1, 2, 3]\n```\n\n**Use `ContiguousArray` when**: No ObjC bridging needed (pure Swift), ~15% faster.\n\n### Reserve Capacity\n\n```swift\n\u002F\u002F ❌ Multiple reallocations\nvar array: [Int] = []\nfor i in 0..\u003C10000 {\n    array.append(i)  \u002F\u002F Reallocates ~14 times\n}\n\n\u002F\u002F ✅ Single allocation\nvar array: [Int] = []\narray.reserveCapacity(10000)\nfor i in 0..\u003C10000 {\n    array.append(i)  \u002F\u002F No reallocations\n}\n```\n\n### Dictionary Hashing\n\n```swift\nstruct BadKey: Hashable {\n    var data: [Int]\n\n    \u002F\u002F ❌ Expensive hash (iterates entire array)\n    func hash(into hasher: inout Hasher) {\n        for element in data {\n            hasher.combine(element)\n        }\n    }\n}\n\nstruct GoodKey: Hashable {\n    var id: UUID  \u002F\u002F Fast hash\n    var data: [Int]  \u002F\u002F Not hashed\n\n    \u002F\u002F ✅ Hash only the unique identifier\n    func hash(into hasher: inout Hasher) {\n        hasher.combine(id)\n    }\n}\n```\n\n### InlineArray (Swift 6.2)\n\nFixed-size arrays stored directly on the stack—no heap allocation, no COW overhead. Uses value generics to encode size in the type.\n\n```swift\n\u002F\u002F Traditional Array - heap allocated, COW overhead\nvar sprites: [Sprite] = Array(repeating: .default, count: 40)\n\n\u002F\u002F InlineArray - stack allocated, no COW (value generic syntax)\nvar sprites = InlineArray\u003C40, Sprite>(repeating: .default)\n```\n\n**Conformances**: `RandomAccessCollection`, `MutableCollection`, `BitwiseCopyable`, `Sendable`. Supports `~Copyable` element types.\n\n**When to Use InlineArray**:\n- Fixed size known at compile time\n- Performance-critical paths (tight loops, hot paths)\n- Want to avoid heap allocation entirely\n- Small to medium sizes (practical limit ~1KB stack usage)\n\nInlineArray is stack-allocated (no heap), eagerly copied (not COW), and provides `.span`\u002F`.mutableSpan` for zero-copy access. Measure your own benchmarks for allocation\u002Fcopy\u002Fmutation trade-offs vs Array.\n\n**Copy Semantics Warning**:\n```swift\n\u002F\u002F ❌ Unexpected: InlineArray copies eagerly\nfunc processLarge(_ data: InlineArray\u003C1000, UInt8>) {\n    \u002F\u002F Copies all 1000 bytes on call!\n}\n\n\u002F\u002F ✅ Use Span to avoid copy\nfunc processLarge(_ data: Span\u003CUInt8>) {\n    \u002F\u002F Zero-copy view, no matter the size\n}\n\n\u002F\u002F Best practice: Store InlineArray, pass Span\nstruct Buffer {\n    var storage = InlineArray\u003C1000, UInt8>(repeating: 0)\n\n    func process() {\n        helper(storage.span)  \u002F\u002F Pass view, not copy\n    }\n}\n```\n\n**When NOT to Use InlineArray**:\n- Dynamic sizes (use Array)\n- Large data (>1KB stack usage risky)\n- Frequently passed by value (use Span instead)\n- Need COW semantics (use Array)\n\n### Lazy Sequences\n\n```swift\n\u002F\u002F ❌ Eager evaluation - processes entire array\nlet result = array\n    .map { expensive($0) }\n    .filter { $0 > 0 }\n    .first  \u002F\u002F Only need first element!\n\n\u002F\u002F ✅ Lazy evaluation - stops at first match\nlet result = array\n    .lazy\n    .map { expensive($0) }\n    .filter { $0 > 0 }\n    .first  \u002F\u002F Only evaluates until first match\n```\n\n---\n\n## Part 8: Concurrency Performance\n\nAsync\u002Fawait and actors add overhead. Use appropriately.\n\n### Actor Isolation Overhead\n\n```swift\nactor Counter {\n    private var value = 0\n\n    \u002F\u002F ❌ Actor call overhead for simple operation\n    func increment() {\n        value += 1\n    }\n}\n\n\u002F\u002F Calling from different isolation domain\nfor _ in 0..\u003C10000 {\n    await counter.increment()  \u002F\u002F 10,000 actor hops!\n}\n\n\u002F\u002F ✅ Batch operations to reduce actor overhead\nactor Counter {\n    private var value = 0\n\n    func incrementBatch(_ count: Int) {\n        value += count\n    }\n}\n\nawait counter.incrementBatch(10000)  \u002F\u002F Single actor hop\n```\n\n### Async Overhead\n\nEach async suspension costs ~20-30μs. Keep synchronous operations synchronous—don't mark a function `async` if it doesn't need to await.\n\n### Task Creation Cost\n\n```swift\n\u002F\u002F ❌ Creating task per item (~100μs overhead each)\nfor item in items {\n    Task {\n        await process(item)\n    }\n}\n\n\u002F\u002F ✅ Single task for batch\nTask {\n    for item in items {\n        await process(item)\n    }\n}\n\n\u002F\u002F ✅ Or use TaskGroup for parallelism\nawait withTaskGroup(of: Void.self) { group in\n    for item in items {\n        group.addTask {\n            await process(item)\n        }\n    }\n}\n```\n\n### `@concurrent` Attribute (Swift 6.2)\n\n```swift\n\u002F\u002F Force background execution\n@concurrent\nfunc expensiveComputation() -> Int {\n    \u002F\u002F Always runs on background thread, even if called from MainActor\n    return complexCalculation()\n}\n\n\u002F\u002F Safe to call from main actor without blocking\n@MainActor\nfunc updateUI() async {\n    let result = await expensiveComputation()  \u002F\u002F Guaranteed off main thread\n    label.text = \"\\(result)\"\n}\n```\n\nFor `nonisolated` performance patterns and detailed actor isolation guidance, see `axiom-swift-concurrency`.\n\n---\n\n## Part 9: Memory Layout\n\nUnderstanding memory layout helps optimize cache performance and reduce allocations.\n\n### Struct Padding\n\n```swift\n\u002F\u002F ❌ Poor layout (24 bytes due to padding)\nstruct BadLayout {\n    var a: Bool    \u002F\u002F 1 byte + 7 padding\n    var b: Int64   \u002F\u002F 8 bytes\n    var c: Bool    \u002F\u002F 1 byte + 7 padding\n}\nprint(MemoryLayout\u003CBadLayout>.size)  \u002F\u002F 24 bytes\n\n\u002F\u002F ✅ Optimized layout (16 bytes)\nstruct GoodLayout {\n    var b: Int64   \u002F\u002F 8 bytes\n    var a: Bool    \u002F\u002F 1 byte\n    var c: Bool    \u002F\u002F 1 byte + 6 padding\n}\nprint(MemoryLayout\u003CGoodLayout>.size)  \u002F\u002F 16 bytes\n```\n\n### Alignment\n\n```swift\n\u002F\u002F Query alignment\nprint(MemoryLayout\u003CDouble>.alignment)  \u002F\u002F 8\nprint(MemoryLayout\u003CInt32>.alignment)   \u002F\u002F 4\n\n\u002F\u002F Structs align to largest member\nstruct Mixed {\n    var int32: Int32   \u002F\u002F 4 bytes, 4-byte aligned\n    var double: Double \u002F\u002F 8 bytes, 8-byte aligned\n}\nprint(MemoryLayout\u003CMixed>.alignment)  \u002F\u002F 8 (largest member)\n```\n\n### Cache-Friendly Data Structures\n\n```swift\n\u002F\u002F ❌ Poor cache locality\nstruct PointerBased {\n    var next: UnsafeMutablePointer\u003CNode>?  \u002F\u002F Pointer chasing\n}\n\n\u002F\u002F ✅ Array-based for cache locality\nstruct ArrayBased {\n    var data: ContiguousArray\u003CInt>  \u002F\u002F Contiguous memory\n}\n\n\u002F\u002F Array iteration ~10x faster due to cache prefetching\n```\n\n### Exclusivity Checks\n\nFrom WWDC 2025-312: Runtime exclusivity enforcement (`swift_beginAccess`\u002F`swift_endAccess`) appears in Time Profiler when the compiler cannot prove memory safety statically.\n\n**What they are**: Swift enforces that no two accesses to the same variable overlap if one is a write. For struct properties, this is checked at compile time. For class stored properties, runtime checks are inserted.\n\n**How to identify**: Look for `swift_beginAccess` and `swift_endAccess` in Time Profiler or Processor Trace flame graphs.\n\n```swift\n\u002F\u002F ❌ Class properties require runtime exclusivity checks\nclass Parser {\n    var state: ParserState\n    var cache: [Int: Pixel]\n\n    func parse() {\n        state.advance()         \u002F\u002F swift_beginAccess \u002F swift_endAccess\n        cache[key] = pixel      \u002F\u002F swift_beginAccess \u002F swift_endAccess\n    }\n}\n\n\u002F\u002F ✅ Struct properties checked at compile time — zero runtime cost\nstruct Parser {\n    var state: ParserState\n    var cache: InlineArray\u003C64, Pixel>\n\n    mutating func parse() {\n        state.advance()         \u002F\u002F No runtime check\n        cache[key] = pixel      \u002F\u002F No runtime check\n    }\n}\n```\n\n**Real-world impact**: In WWDC 2025-312's QOI image parser, moving properties from a class to a struct eliminated all runtime exclusivity checks, contributing to a measurable speedup as part of a >700x total improvement.\n\n---\n\n## Part 10: Typed Throws (Swift 6)\n\nTyped throws can be faster than untyped by avoiding existential overhead.\n\n### Untyped vs Typed\n\n```swift\n\u002F\u002F Untyped - existential container for error\nfunc fetchData() throws -> Data {\n    \u002F\u002F Can throw any Error\n    throw NetworkError.timeout\n}\n\n\u002F\u002F Typed - concrete error type\nfunc fetchData() throws(NetworkError) -> Data {\n    \u002F\u002F Can only throw NetworkError\n    throw NetworkError.timeout\n}\n```\n\n### Performance Impact\n\n```swift\n\u002F\u002F Measure with tight loop\nfunc untypedThrows() throws -> Int {\n    throw GenericError.failed\n}\n\nfunc typedThrows() throws(GenericError) -> Int {\n    throw GenericError.failed\n}\n\n\u002F\u002F Benchmark: typed ~5-10% faster (no existential overhead)\n```\n\n### When to Use\n\n- **Typed**: Library code with well-defined error types, hot paths\n- **Untyped**: Application code, error types unknown at compile time\n\n---\n\n## Part 11: Span Types\n\n**Swift 6.2+** introduces Span—a non-escapable, non-owning view into memory that provides safe, efficient access to contiguous data.\n\n### What is Span?\n\nSpan is a modern replacement for `UnsafeBufferPointer` that provides:\n- **Spatial safety**: Bounds-checked operations prevent out-of-bounds access\n- **Temporal safety**: Lifetime inherited from source, preventing use-after-free\n- **Zero overhead**: No heap allocation, no reference counting\n- **Non-escapable**: Cannot outlive the data it references\n\n```swift\n\u002F\u002F Traditional unsafe approach\nfunc processUnsafe(_ data: UnsafeMutableBufferPointer\u003CUInt8>) {\n    data[100] = 0  \u002F\u002F Crashes if out of bounds!\n}\n\n\u002F\u002F Safe Span approach\nfunc processSafe(_ data: MutableSpan\u003CUInt8>) {\n    data[100] = 0  \u002F\u002F Traps with clear error if out of bounds\n}\n```\n\n### When to Use Span vs Array vs UnsafeBufferPointer\n\n| Use Case | Recommendation |\n|----------|---------------|\n| **Own the data** | Array (full ownership, COW) |\n| **Temporary view for reading** | Span (safe, fast) |\n| **Temporary view for writing** | MutableSpan (safe, fast) |\n| **C interop, performance-critical** | RawSpan (untyped bytes) |\n| **Unsafe performance** | UnsafeBufferPointer (legacy, avoid) |\n\n### Basic Span Usage\n\n```swift\nlet array = [1, 2, 3, 4, 5]\nlet span = array.span        \u002F\u002F Read-only view\nprint(span[0])               \u002F\u002F Subscript access\nfor element in span { }      \u002F\u002F Safe iteration\nlet slice = span[1..\u003C3]      \u002F\u002F Span slice, no copy\n```\n\n### MutableSpan for Modifications\n\n```swift\nvar array = [10, 20, 30, 40, 50]\nlet mutableSpan = array.mutableSpan\nmutableSpan[0] = 100  \u002F\u002F Modifies array in-place, bounds-checked\n```\n\n### RawSpan for Untyped Bytes\n\n```swift\nfunc parsePacket(_ data: RawSpan) -> PacketHeader? {\n    guard data.count >= MemoryLayout\u003CPacketHeader>.size else { return nil }\n    \u002F\u002F Safe byte-level access via subscript\n    return PacketHeader(version: data[0], flags: data[1],\n        length: UInt16(data[3]) \u003C\u003C 8 | UInt16(data[2]))\n}\n\nlet header = parsePacket(bytes.rawSpan)  \u002F\u002F .rawSpan on any [UInt8]\n```\n\nAll Swift 6.2 collections provide `.span` and `.mutableSpan` properties, including `Array`, `ContiguousArray`, and `UnsafeBufferPointer` (migration path). Span access speed matches `UnsafeBufferPointer` (~2ns) with bounds checking.\n\n### Non-Escapable Lifetime Safety\n\nSpan's lifetime is bound to its source. The compiler prevents returning a Span from a function where the source would be deallocated — unlike `UnsafeBufferPointer`, which allows this bug silently.\n\n```swift\nfunc dangerousSpan() -> Span\u003CInt> {\n    let array = [1, 2, 3]\n    return array.span  \u002F\u002F ❌ Error: Cannot return non-escapable value\n}\n```\n\nInlineArray also provides `.span`\u002F`.mutableSpan` — see Part 7 for InlineArray usage and copy-avoidance via Span.\n\n### Migration from UnsafeBufferPointer\n\n```swift\n\u002F\u002F ❌ Old: unsafe, no bounds checking\nfunc parseLegacy(_ buffer: UnsafeBufferPointer\u003CUInt8>) -> Header {\n    Header(magic: buffer[0], version: buffer[1])  \u002F\u002F Silent OOB crash\n}\n\n\u002F\u002F ✅ New: safe, bounds-checked, same performance\nfunc parseModern(_ span: Span\u003CUInt8>) -> Header {\n    Header(magic: span[0], version: span[1])  \u002F\u002F Traps on OOB\n}\n\n\u002F\u002F Bridge: existing UnsafeBufferPointer → Span\nlet span = buffer.span  \u002F\u002F Wrap unsafe in safe span\nparseModern(span)\n```\n\n### OutputSpan — Safe Initialization\n\nOutputSpan\u002FOutputRawSpan replace `UnsafeMutableBufferPointer` for initializing new collections without intermediate allocations.\n\n```swift\n\u002F\u002F Binary serialization: write header bytes safely\n@lifetime(&output)\nfunc writeHeader(to output: inout OutputRawSpan) {\n    output.append(0x01)       \u002F\u002F version\n    output.append(0x00)       \u002F\u002F flags\n    output.append(UInt16(42)) \u002F\u002F length (type-safe)\n}\n```\n\nUse for building byte arrays, binary serialization, image pixel data. Apple's open-source [Swift Binary Parsing](https:\u002F\u002Fgithub.com\u002Fapple\u002Fswift-binary-parsing) library is built entirely on Span types.\n\n### When NOT to Use Span\n\n- **Ownership**: Span can't be stored in structs\u002Fclasses — use Array for owned data, provide `.span` access via computed property\n- **Return values**: Span is non-escapable — process in scope, return owned data\n- **Long-lived references**: Span lifetime is bound to source — use Array if data must outlive the current scope\n\n---\n\n## Copy-Paste Patterns\n\n### Pattern 1: COW Wrapper\n\n```swift\nfinal class Storage\u003CT> {\n    var value: T\n    init(_ value: T) { self.value = value }\n}\n\nstruct COWWrapper\u003CT> {\n    private var storage: Storage\u003CT>\n\n    init(_ value: T) {\n        storage = Storage(value)\n    }\n\n    var value: T {\n        get { storage.value }\n        set {\n            if !isKnownUniquelyReferenced(&storage) {\n                storage = Storage(newValue)\n            } else {\n                storage.value = newValue\n            }\n        }\n    }\n}\n```\n\n### Pattern 2: Performance-Critical Loop\n\n```swift\nfunc processLargeArray(_ input: [Int]) -> [Int] {\n    var result = ContiguousArray\u003CInt>()\n    result.reserveCapacity(input.count)\n\n    for element in input {\n        result.append(transform(element))\n    }\n\n    return Array(result)\n}\n```\n\n### Pattern 3: Inline Cache Lookup\n\n```swift\nprivate var cache: [Key: Value] = [:]\n\n@inlinable\nfunc getCached(_ key: Key) -> Value? {\n    return cache[key]  \u002F\u002F Inlined across modules\n}\n```\n\n---\n\n## Anti-Patterns\n\n| Anti-Pattern | Problem | Fix |\n|---|---|---|\n| **Premature optimization** | Complex COW\u002FContiguousArray with no profiling data | Start simple, profile, optimize what matters |\n| **Weak everywhere** | `weak` on every delegate (atomic overhead) | Use `unowned` when lifetime is guaranteed (see Part 4) |\n| **Actor for everything** | Actor isolation on simple counters (~100μs\u002Fcall) | Use lock-free atomics (`ManagedAtomic`) for simple sync data |\n\n---\n\n## Code Review Checklist\n\n### Memory Management\n- [ ] Large structs (>64 bytes) use indirect storage or are classes\n- [ ] COW types use `isKnownUniquelyReferenced` before mutation\n- [ ] Collections use `reserveCapacity` when size is known\n- [ ] Weak references only where needed (prefer unowned when safe)\n\n### Generics\n- [ ] Protocol types use `some` instead of `any` where possible\n- [ ] Hot paths use concrete types or `@_specialize`\n- [ ] Generic constraints are as specific as possible\n\n### Collections\n- [ ] Pure Swift code uses `ContiguousArray` over `Array`\n- [ ] Dictionary keys have efficient `hash(into:)` implementations\n- [ ] Lazy evaluation used for short-circuit operations\n\n### Concurrency\n- [ ] Synchronous operations don't use `async`\n- [ ] Actor calls are batched when possible\n- [ ] Task creation is minimized (use TaskGroup)\n- [ ] CPU-intensive work uses `@concurrent` (Swift 6.2)\n\n### Optimization\n- [ ] Profiling data exists before optimization\n- [ ] Inlining only for small, frequently called functions\n- [ ] Memory layout optimized for cache locality (large structs)\n\n---\n\n## Pressure Scenarios\n\n### Scenario 1: \"Just make it faster, we ship tomorrow\"\n\n**The Pressure**: Manager sees \"slow\" in profiler, demands immediate action.\n\n**Red Flags**:\n- No baseline measurements\n- No Time Profiler data showing hotspots\n- \"Make everything faster\" without targets\n\n**Time Cost Comparison**:\n- Premature optimization: 2 days of work, no measurable improvement\n- Profile-guided optimization: 2 hours profiling + 4 hours fixing actual bottleneck = 40% faster\n\n**How to Push Back Professionally**:\n```\n\"I want to optimize effectively. Let me spend 30 minutes with Instruments\nto find the actual bottleneck. This prevents wasting time on code that's\nnot the problem. I've seen this save days of work.\"\n```\n\n### Scenario 2: \"Use actors everywhere for thread safety\"\n\n**The Pressure**: Team adopts Swift 6, decides \"everything should be an actor.\"\n\n**Red Flags**:\n- Actor for simple value types\n- Actor for synchronous-only operations\n- Async overhead in tight loops\n\n**Time Cost Comparison**:\n- Actor everywhere: 100μs overhead per operation, janky UI\n- Appropriate isolation: 10μs overhead, smooth 60fps\n\n**How to Push Back Professionally**:\n```\n\"Actors are great for isolation, but they add overhead. For this simple\ncounter, lock-free atomics are 10x faster. Let's use actors where we need\nthem—shared mutable state—and avoid them for pure value types.\"\n```\n\n### Scenario 3: \"Inline everything for speed\"\n\n**The Pressure**: Someone reads that inlining is faster, marks everything `@inlinable`.\n\n**Red Flags**:\n- Large functions marked `@inlinable`\n- Internal implementation details exposed\n- Binary size increases 50%\n\n**Time Cost Comparison**:\n- Inline everything: Code bloat, slower app launch (3s → 5s)\n- Selective inlining: Fast launch, actual hotspots optimized\n\n**How to Push Back Professionally**:\n```\n\"Inlining trades code size for speed. The compiler already inlines when\nbeneficial. Manual @inlinable should be for small, frequently called\nfunctions. Let's profile and inline the 3 actual hotspots, not everything.\"\n```\n\n---\n\n## Real-World Examples\n\n### Example 1: Image Processing Pipeline\n\n**Problem**: Processing 1000 images takes 30 seconds.\n\n**Investigation**:\n```swift\n\u002F\u002F Original code\nfunc processImages(_ images: [UIImage]) -> [ProcessedImage] {\n    var results: [ProcessedImage] = []\n    for image in images {\n        results.append(expensiveProcess(image))  \u002F\u002F Reallocations!\n    }\n    return results\n}\n```\n\n**Solution**:\n```swift\nfunc processImages(_ images: [UIImage]) -> [ProcessedImage] {\n    var results = ContiguousArray\u003CProcessedImage>()\n    results.reserveCapacity(images.count)  \u002F\u002F Single allocation\n\n    for image in images {\n        results.append(expensiveProcess(image))\n    }\n\n    return Array(results)\n}\n```\n\n**Result**: 30s → 8s (73% faster) by eliminating reallocations.\n\n### Example 2: Generic Specialization\n\n**Problem**: Protocol-based rendering is slow.\n\n**Investigation**:\n```swift\n\u002F\u002F Original - existential overhead\nfunc render(shapes: [any Shape]) {\n    for shape in shapes {\n        shape.draw()  \u002F\u002F Dynamic dispatch\n    }\n}\n```\n\n**Solution**:\n```swift\n\u002F\u002F Specialized generic\nfunc render\u003CS: Shape>(shapes: [S]) {\n    for shape in shapes {\n        shape.draw()  \u002F\u002F Static dispatch after specialization\n    }\n}\n\n\u002F\u002F Or use @_specialize\n@_specialize(where S == Circle)\n@_specialize(where S == Rectangle)\nfunc render\u003CS: Shape>(shapes: [S]) { }\n```\n\n**Result**: 100ms → 10ms (10x faster) by eliminating witness table overhead.\n\n---\n\n## Resources\n\n**WWDC**: 2025-312, 2024-10217, 2024-10170, 2021-10216, 2016-416\n\n**Docs**: \u002Fswift\u002Finlinearray, \u002Fswift\u002Fspan, \u002Fswift\u002Foutputspan\n\n**Skills**: axiom-performance-profiling, axiom-swift-concurrency, axiom-swiftui-performance\n\n---\n\n","# Swift Performance Optimization\n\n## Purpose\n\n**Core Principle**: Optimize Swift code by understanding language-level performance characteristics—value semantics, ARC behavior, generic specialization, and memory layout—to write fast, efficient code without premature micro-optimization.\n\n**Swift Version**: Swift 6.2+ (for InlineArray, Span, `@concurrent`)\n**Xcode**: 16+\n**Platforms**: iOS 18+, macOS 15+\n\n**Related Skills**:\n- `axiom-performance-profiling` — Use Instruments to measure (do this first!)\n- `axiom-swiftui-performance` — SwiftUI-specific optimizations\n- `axiom-build-performance` — Compilation speed\n- `axiom-swift-concurrency` — Correctness-focused concurrency patterns\n\n## When to Use This Skill\n\n### ✅ Use this skill when\n\n- App profiling shows Swift code as the bottleneck (Time Profiler hotspots)\n- Excessive memory allocations or retain\u002Frelease traffic\n- Implementing performance-critical algorithms or data structures\n- Writing framework or library code with performance requirements\n- Optimizing tight loops or frequently called methods\n- Dealing with large data structures or collections\n- Code review identifying performance anti-patterns\n\n## Quick Decision Tree\n\n```\nPerformance issue identified?\n│\n├─ Profiler shows excessive copying?\n│  └─ → Part 1: Noncopyable Types\n│  └─ → Part 2: Copy-on-Write\n│\n├─ Retain\u002Frelease overhead in Time Profiler?\n│  └─ → Part 4: ARC Optimization\n│\n├─ Generic code in hot path?\n│  └─ → Part 5: Generics & Specialization\n│\n├─ Collection operations slow?\n│  └─ → Part 7: Collection Performance\n│\n├─ Async\u002Fawait overhead visible?\n│  └─ → Part 8: Concurrency Performance\n│\n├─ Struct vs class decision?\n│  └─ → Part 3: Value vs Reference\n│\n└─ Memory layout concerns?\n   └─ → Part 9: Memory Layout\n```\n\n---\n\n## The Four Principles of Swift Performance\n\nFrom WWDC 2024-10217: Swift's low-level performance characteristics come down to four areas. Each maps to a Part in this skill.\n\n| Principle | What It Costs | Skill Coverage |\n|-----------|--------------|----------------|\n| **Function Calls** | Dispatch overhead, optimization barriers | Part 5 (Generics), Part 6 (Inlining) |\n| **Memory Allocation** | Stack vs heap, allocation frequency | Part 3 (Value vs Reference), Part 7 (Collections) |\n| **Memory Layout** | Cache locality, padding, contiguity | Part 9 (Memory Layout), Part 11 (Span) |\n| **Value Copying** | COW triggers, defensive copies, ARC traffic | Part 1 (Noncopyable), Part 2 (COW), Part 4 (ARC) |\n\nUnderstanding which principle is causing your bottleneck determines which Part to use.\n\n---\n\n## Part 1: Noncopyable Types (~Copyable)\n\n**Swift 6.0+** introduces noncopyable types for performance-critical scenarios where you want to avoid implicit copies.\n\n### When to Use\n\n- Large types that should never be copied (file handles, GPU buffers)\n- Types with ownership semantics (must be explicitly consumed)\n- Performance-critical code where copies are expensive\n\n### Basic Pattern\n\n```swift\n\u002F\u002F Noncopyable type\nstruct FileHandle: ~Copyable {\n    private let fd: Int32\n\n    init(path: String) throws {\n        self.fd = open(path, O_RDONLY)\n        guard fd != -1 else { throw FileError.openFailed }\n    }\n\n    deinit {\n        close(fd)\n    }\n\n    \u002F\u002F Must explicitly consume\n    consuming func close() {\n        _ = consume self\n    }\n}\n\n\u002F\u002F Usage\nfunc processFile() throws {\n    let handle = try FileHandle(path: \"\u002Fdata.txt\")\n    \u002F\u002F handle is automatically consumed at end of scope\n    \u002F\u002F Cannot accidentally copy handle\n}\n```\n\n### Ownership Annotations\n\n```swift\n\u002F\u002F consuming - takes ownership, caller cannot use after\nfunc process(consuming data: [UInt8]) {\n    \u002F\u002F data is consumed\n}\n\n\u002F\u002F borrowing - temporary access without ownership\nfunc validate(borrowing data: [UInt8]) -> Bool {\n    \u002F\u002F data can still be used by caller\n    return data.count > 0\n}\n\n\u002F\u002F inout - mutable access\nfunc modify(inout data: [UInt8]) {\n    data.append(0)\n}\n```\n\n### Performance Impact\n\n- **Eliminates implicit copies**: Compiler error instead of runtime copy\n- **Zero-cost abstraction**: Same performance as manual memory management\n- **Use when**: Type is expensive to copy (>64 bytes) and copies are rare\n\n---\n\n## Part 2: Copy-on-Write (COW)\n\nSwift collections use COW for efficient memory sharing. Understanding when copies happen is critical for performance.\n\n### How COW Works\n\n```swift\nvar array1 = [1, 2, 3]  \u002F\u002F Single allocation\nvar array2 = array1     \u002F\u002F Share storage (no copy)\narray2.append(4)        \u002F\u002F Now copies (array1 modified array2)\n```\n\nFor custom COW implementation, see Copy-Paste Pattern 1 (COW Wrapper) below.\n\n### Performance Tips\n\n```swift\n\u002F\u002F ❌ Accidental copy in loop\nfor i in 0..\u003Carray.count {\n    array[i] = transform(array[i])  \u002F\u002F Copy on first mutation if shared!\n}\n\n\u002F\u002F ✅ Reserve capacity first (ensures unique)\narray.reserveCapacity(array.count)\nfor i in 0..\u003Carray.count {\n    array[i] = transform(array[i])\n}\n\n\u002F\u002F ❌ Multiple mutations trigger multiple uniqueness checks\narray.append(1)\narray.append(2)\narray.append(3)\n\n\u002F\u002F ✅ Single reservation\narray.reserveCapacity(array.count + 3)\narray.append(contentsOf: [1, 2, 3])\n```\n\n### Defensive Copies\n\nFrom WWDC 2024-10217: Swift sometimes inserts *defensive copies* when it cannot prove a value won't be mutated through a shared reference.\n\n```swift\nclass DataStore {\n    var items: [Item] = []  \u002F\u002F COW type stored in class\n}\n\nfunc process(_ store: DataStore) {\n    for item in store.items {\n        \u002F\u002F Swift may defensively copy `items` because:\n        \u002F\u002F 1. store.items is a class property (another reference could mutate it)\n        \u002F\u002F 2. The loop needs a stable snapshot\n        handle(item)\n    }\n}\n```\n\n**How to avoid**: Copy to a local variable first — one explicit copy instead of repeated defensive copies:\n\n```swift\nfunc process(_ store: DataStore) {\n    let items = store.items  \u002F\u002F One copy\n    for item in items {\n        handle(item)  \u002F\u002F No more defensive copies\n    }\n}\n```\n\n**In profiler**: Defensive copies appear as unexpected `swift_retain`\u002F`swift_release` pairs or `Array.__allocating_init` calls when you didn't expect allocation.\n\n---\n\n## Part 3: Value vs Reference Semantics\n\nChoosing between `struct` and `class` has significant performance implications.\n\n### Decision Matrix\n\n| Factor | Use Struct | Use Class |\n|--------|-----------|-----------|\n| **Size** | ≤ 64 bytes | > 64 bytes or contains large data |\n| **Identity** | No identity needed | Needs identity (===) |\n| **Inheritance** | Not needed | Inheritance required |\n| **Mutation** | Infrequent | Frequent in-place updates |\n| **Sharing** | No sharing needed | Must be shared across scope |\n\n### Small Structs (Fast)\n\n```swift\n\u002F\u002F ✅ Fast - fits in registers, no heap allocation\nstruct Point {\n    var x: Double  \u002F\u002F 8 bytes\n    var y: Double  \u002F\u002F 8 bytes\n}  \u002F\u002F Total: 16 bytes - excellent for struct\n\nstruct Color {\n    var r, g, b, a: UInt8  \u002F\u002F 4 bytes total - perfect for struct\n}\n```\n\n### Large Structs (Slow)\n\n```swift\n\u002F\u002F ❌ Slow - excessive copying\nstruct HugeData {\n    var buffer: [UInt8]  \u002F\u002F 1MB\n    var metadata: String\n}\n\nfunc process(_ data: HugeData) {  \u002F\u002F Copies 1MB!\n    \u002F\u002F ...\n}\n\n\u002F\u002F ✅ Use reference semantics for large data\nfinal class HugeData {\n    var buffer: [UInt8]\n    var metadata: String\n}\n\nfunc process(_ data: HugeData) {  \u002F\u002F Only copies pointer (8 bytes)\n    \u002F\u002F ...\n}\n```\n\n### Indirect Storage for Flexibility\n\nFor large data that needs value semantics externally with reference storage internally, use the COW Wrapper pattern — see Copy-Paste Pattern 1 below.\n\n---\n\n## Part 4: ARC Optimization\n\nAutomatic Reference Counting adds overhead. Minimize it where possible.\n\n### Weak vs Unowned Performance\n\n```swift\nclass Parent {\n    var child: Child?\n}\n\nclass Child {\n    \u002F\u002F ❌ Weak adds overhead (optional, thread-safe zeroing)\n    weak var parent: Parent?\n}\n\n\u002F\u002F ✅ Unowned when you know lifetime guarantees\nclass Child {\n    unowned let parent: Parent  \u002F\u002F No overhead, crashes if parent deallocated\n}\n```\n\n**Performance**: `unowned` is ~2x faster than `weak` (no atomic operations).\n\n**Use when**: Child lifetime \u003C Parent lifetime (guaranteed).\n\n### Closure Capture Optimization\n\n```swift\nclass DataProcessor {\n    var data: [Int]\n\n    \u002F\u002F ❌ Captures self strongly, then uses weak - unnecessary weak overhead\n    func process(completion: @escaping () -> Void) {\n        DispatchQueue.global().async { [weak self] in\n            guard let self else { return }\n            self.data.forEach { print($0) }\n            completion()\n        }\n    }\n\n    \u002F\u002F ✅ Capture only what you need\n    func process(completion: @escaping () -> Void) {\n        let data = self.data  \u002F\u002F Copy value type\n        DispatchQueue.global().async {\n            data.forEach { print($0) }  \u002F\u002F No self captured\n            completion()\n        }\n    }\n}\n```\n\n### Closure Capture Costs\n\nFrom WWDC 2024-10217: Closures have different performance profiles depending on whether they escape.\n\n```swift\n\u002F\u002F Non-escaping closure — stack-allocated context, zero ARC overhead\nfunc processItems(_ items: [Item], using transform: (Item) -> Result) -> [Result] {\n    items.map(transform)  \u002F\u002F Closure context lives on stack\n}\n\n\u002F\u002F Escaping closure — heap-allocated context, ARC on every captured reference\nfunc processItemsLater(_ items: [Item], transform: @escaping (Item) -> Result) {\n    \u002F\u002F Closure context heap-allocated as anonymous class instance\n    \u002F\u002F Each captured reference gets retain\u002Frelease\n    self.pending = { items.map(transform) }\n}\n```\n\n**Why this matters**: `@Sendable` closures are always escaping, meaning every Task closure heap-allocates its capture context.\n\n**In hot paths**: Prefer non-escaping closures. If you see `swift_allocObject` in Time Profiler for closure contexts, look for escaping closures that could be non-escaping.\n\n### Observable Object Lifetimes\n\n**From WWDC 2021-10216**: Object lifetimes end at **last use**, not at closing brace.\n\n```swift\n\u002F\u002F ❌ Relying on observed lifetime is fragile\nclass Traveler {\n    weak var account: Account?\n\n    deinit {\n        print(\"Deinitialized\")  \u002F\u002F May run BEFORE expected with ARC optimizations!\n    }\n}\n\nfunc test() {\n    let traveler = Traveler()\n    let account = Account(traveler: traveler)\n    \u002F\u002F traveler's last use is above - may deallocate here!\n    account.printSummary()  \u002F\u002F weak reference may be nil!\n}\n\n\u002F\u002F ✅ Explicitly extend lifetime when needed\nfunc test() {\n    let traveler = Traveler()\n    let account = Account(traveler: traveler)\n\n    withExtendedLifetime(traveler) {\n        account.printSummary()  \u002F\u002F traveler guaranteed to live\n    }\n}\n```\n\nObject lifetimes can change between Xcode versions, Debug vs Release, and unrelated code changes. Enable \"Optimize Object Lifetimes\" (Xcode 13+) during development to expose hidden lifetime bugs early.\n\n---\n\n## Part 5: Generics & Specialization\n\nGeneric code can be fast or slow depending on specialization.\n\n### Specialization Basics\n\n```swift\n\u002F\u002F Generic function\nfunc process\u003CT>(_ value: T) {\n    print(value)\n}\n\n\u002F\u002F Calling with concrete type\nprocess(42)  \u002F\u002F Compiler specializes: process_Int(42)\nprocess(\"hello\")  \u002F\u002F Compiler specializes: process_String(\"hello\")\n```\n\n### Existential Overhead\n\n```swift\nprotocol Drawable {\n    func draw()\n}\n\n\u002F\u002F ❌ Existential container - expensive (heap allocation, indirection)\nfunc drawAll(shapes: [any Drawable]) {\n    for shape in shapes {\n        shape.draw()  \u002F\u002F Dynamic dispatch through witness table\n    }\n}\n\n\u002F\u002F ✅ Generic with constraint - can specialize\nfunc drawAll\u003CT: Drawable>(shapes: [T]) {\n    for shape in shapes {\n        shape.draw()  \u002F\u002F Static dispatch after specialization\n    }\n}\n```\n\n**Performance**: Generic version ~10x faster (eliminates witness table overhead).\n\n### Existential Container Overhead\n\n**From WWDC 2016-416**: `any Protocol` uses a 40-byte existential container (5 words on 64-bit). The container stores type metadata + protocol witness table (16 bytes) plus a 24-byte inline value buffer. Types ≤24 bytes are stored directly in the buffer (fast, ~5ns access); larger types require a heap allocation with pointer indirection (slower, ~15ns). `some Protocol` eliminates all container overhead (~2ns).\n\n**When `some` isn't available** (heterogeneous collections require `any`):\n- **Reduce type sizes to ≤24 bytes** — keep protocol-conforming types small enough for inline storage (3 words: e.g., `Point { x, y, z: Double }` fits exactly)\n- **Use enum dispatch instead** — eliminates containers entirely, trades open extensibility for performance:\n\n```swift\n\u002F\u002F ❌ Existential: 40 bytes\u002Felement, witness table dispatch\nlet shapes: [any Drawable] = [circle, rect]\n\n\u002F\u002F ✅ Enum: value-sized, static dispatch via switch\nenum Shape { case circle(Circle), rect(Rect) }\nfunc draw(_ shape: Shape) {\n    switch shape {\n    case .circle(let c): c.draw()\n    case .rect(let r): r.draw()\n    }\n}\n```\n\n- **Batch operations** — amortize per-element existential overhead by processing in chunks rather than one-at-a-time\n- **Measure first** — existential overhead (~10ns\u002Faccess) only matters in tight loops; for UI-level code it's negligible\n\n### `@_specialize` Attribute\n\nForce specialization for common types when the compiler doesn't do it automatically:\n\n```swift\n@_specialize(where T == Int)\n@_specialize(where T == String)\nfunc process\u003CT: Comparable>(_ value: T) -> T { value }\n\u002F\u002F Generates specialized versions + generic fallback\n```\n\n---\n\n## Part 6: Inlining\n\nInlining eliminates function call overhead but increases code size.\n\n### When to Inline\n\n```swift\n\u002F\u002F ✅ Small, frequently called functions\n@inlinable\npublic func fastAdd(_ a: Int, _ b: Int) -> Int {\n    return a + b\n}\n\n\u002F\u002F ❌ Large functions - code bloat\n@inlinable  \u002F\u002F Don't do this!\npublic func complexAlgorithm() {\n    \u002F\u002F 100 lines of code...\n}\n```\n\n### Cross-Module Optimization\n\n```swift\n\u002F\u002F Framework code\npublic struct Point {\n    public var x: Double\n    public var y: Double\n\n    \u002F\u002F ✅ Inlinable for cross-module optimization\n    @inlinable\n    public func distance(to other: Point) -> Double {\n        let dx = x - other.x\n        let dy = y - other.y\n        return sqrt(dx*dx + dy*dy)\n    }\n}\n\n\u002F\u002F Client code\nlet p1 = Point(x: 0, y: 0)\nlet p2 = Point(x: 3, y: 4)\nlet d = p1.distance(to: p2)  \u002F\u002F Inlined across module boundary\n```\n\n### `@usableFromInline`\n\n```swift\n\u002F\u002F Internal helper that can be inlined\n@usableFromInline\ninternal func helperFunction() { }\n\n\u002F\u002F Public API that uses it\n@inlinable\npublic func publicAPI() {\n    helperFunction()  \u002F\u002F Can inline internal function\n}\n```\n\n**Trade-off**: `@inlinable` exposes implementation, prevents future optimization.\n\n---\n\n## Part 7: Collection Performance\n\nChoosing the right collection and using it correctly matters.\n\n### Array vs ContiguousArray\n\n```swift\n\u002F\u002F ❌ Array\u003CT> - may use NSArray bridging (Swift\u002FObjC interop)\nlet array: Array\u003CInt> = [1, 2, 3]\n\n\u002F\u002F ✅ ContiguousArray\u003CT> - guaranteed contiguous memory (no bridging)\nlet array: ContiguousArray\u003CInt> = [1, 2, 3]\n```\n\n**Use `ContiguousArray` when**: No ObjC bridging needed (pure Swift), ~15% faster.\n\n### Reserve Capacity\n\n```swift\n\u002F\u002F ❌ Multiple reallocations\nvar array: [Int] = []\nfor i in 0..\u003C10000 {\n    array.append(i)  \u002F\u002F Reallocates ~14 times\n}\n\n\u002F\u002F ✅ Single allocation\nvar array: [Int] = []\narray.reserveCapacity(10000)\nfor i in 0..\u003C10000 {\n    array.append(i)  \u002F\u002F No reallocations\n}\n```\n\n### Dictionary Hashing\n\n```swift\nstruct BadKey: Hashable {\n    var data: [Int]\n\n    \u002F\u002F ❌ Expensive hash (iterates entire array)\n    func hash(into hasher: inout Hasher) {\n        for element in data {\n            hasher.combine(element)\n        }\n    }\n}\n\nstruct GoodKey: Hashable {\n    var id: UUID  \u002F\u002F Fast hash\n    var data: [Int]  \u002F\u002F Not hashed\n\n    \u002F\u002F ✅ Hash only the unique identifier\n    func hash(into hasher: inout Hasher) {\n        hasher.combine(id)\n    }\n}\n```\n\n### InlineArray (Swift 6.2)\n\nFixed-size arrays stored directly on the stack—no heap allocation, no COW overhead. Uses value generics to encode size in the type.\n\n```swift\n\u002F\u002F Traditional Array - heap allocated, COW overhead\nvar sprites: [Sprite] = Array(repeating: .default, count: 40)\n\n\u002F\u002F InlineArray - stack allocated, no COW (value generic syntax)\nvar sprites = InlineArray\u003C40, Sprite>(repeating: .default)\n```\n\n**Conformances**: `RandomAccessCollection`, `MutableCollection`, `BitwiseCopyable`, `Sendable`. Supports `~Copyable` element types.\n\n**When to Use InlineArray**:\n- Fixed size known at compile time\n- Performance-critical paths (tight loops, hot paths)\n- Want to avoid heap allocation entirely\n- Small to medium sizes (practical limit ~1KB stack usage)\n\nInlineArray is stack-allocated (no heap), eagerly copied (not COW), and provides `.span`\u002F`.mutableSpan` for zero-copy access. Measure your own benchmarks for allocation\u002Fcopy\u002Fmutation trade-offs vs Array.\n\n**Copy Semantics Warning**:\n```swift\n\u002F\u002F ❌ Unexpected: InlineArray copies eagerly\nfunc processLarge(_ data: InlineArray\u003C1000, UInt8>) {\n    \u002F\u002F Copies all 1000 bytes on call!\n}\n\n\u002F\u002F ✅ Use Span to avoid copy\nfunc processLarge(_ data: Span\u003CUInt8>) {\n    \u002F\u002F Zero-copy view, no matter the size\n}\n\n\u002F\u002F Best practice: Store InlineArray, pass Span\nstruct Buffer {\n    var storage = InlineArray\u003C1000, UInt8>(repeating: 0)\n\n    func process() {\n        helper(storage.span)  \u002F\u002F Pass view, not copy\n    }\n}\n```\n\n**When NOT to Use InlineArray**:\n- Dynamic sizes (use Array)\n- Large data (>1KB stack usage risky)\n- Frequently passed by value (use Span instead)\n- Need COW semantics (use Array)\n\n### Lazy Sequences\n\n```swift\n\u002F\u002F ❌ Eager evaluation - processes entire array\nlet result = array\n    .map { expensive($0) }\n    .filter { $0 > 0 }\n    .first  \u002F\u002F Only need first element!\n\n\u002F\u002F ✅ Lazy evaluation - stops at first match\nlet result = array\n    .lazy\n    .map { expensive($0) }\n    .filter { $0 > 0 }\n    .first  \u002F\u002F Only evaluates until first match\n```\n\n---\n\n## Part 8: Concurrency Performance\n\nAsync\u002Fawait and actors add overhead. Use appropriately.\n\n### Actor Isolation Overhead\n\n```swift\nactor Counter {\n    private var value = 0\n\n    \u002F\u002F ❌ Actor call overhead for simple operation\n    func increment() {\n        value += 1\n    }\n}\n\n\u002F\u002F Calling from different isolation domain\nfor _ in 0..\u003C10000 {\n    await counter.increment()  \u002F\u002F 10,000 actor hops!\n}\n\n\u002F\u002F ✅ Batch operations to reduce actor overhead\nactor Counter {\n    private var value = 0\n\n    func incrementBatch(_ count: Int) {\n        value += count\n    }\n}\n\nawait counter.incrementBatch(10000)  \u002F\u002F Single actor hop\n```\n\n### Async Overhead\n\nEach async suspension costs ~20-30μs. Keep synchronous operations synchronous—don't mark a function `async` if it doesn't need to await.\n\n### Task Creation Cost\n\n```swift\n\u002F\u002F ❌ Creating task per item (~100μs overhead each)\nfor item in items {\n    Task {\n        await process(item)\n    }\n}\n\n\u002F\u002F ✅ Single task for batch\nTask {\n    for item in items {\n        await process(item)\n    }\n}\n\n\u002F\u002F ✅ Or use TaskGroup for parallelism\nawait withTaskGroup(of: Void.self) { group in\n    for item in items {\n        group.addTask {\n            await process(item)\n        }\n    }\n}\n```\n\n### `@concurrent` Attribute (Swift 6.2)\n\n```swift\n\u002F\u002F Force background execution\n@concurrent\nfunc expensiveComputation() -> Int {\n    \u002F\u002F Always runs on background thread, even if called from MainActor\n    return complexCalculation()\n}\n\n\u002F\u002F Safe to call from main actor without blocking\n@MainActor\nfunc updateUI() async {\n    let result = await expensiveComputation()  \u002F\u002F Guaranteed off main thread\n    label.text = \"\\(result)\"\n}\n```\n\nFor `nonisolated` performance patterns and detailed actor isolation guidance, see `axiom-swift-concurrency`.\n\n---\n\n## Part 9: Memory Layout\n\nUnderstanding memory layout helps optimize cache performance and reduce allocations.\n\n### Struct Padding\n\n```swift\n\u002F\u002F ❌ Poor layout (24 bytes due to padding)\nstruct BadLayout {\n    var a: Bool    \u002F\u002F 1 byte + 7 padding\n    var b: Int64   \u002F\u002F 8 bytes\n    var c: Bool    \u002F\u002F 1 byte + 7 padding\n}\nprint(MemoryLayout\u003CBadLayout>.size)  \u002F\u002F 24 bytes\n\n\u002F\u002F ✅ Optimized layout (16 bytes)\nstruct GoodLayout {\n    var b: Int64   \u002F\u002F 8 bytes\n    var a: Bool    \u002F\u002F 1 byte\n    var c: Bool    \u002F\u002F 1 byte + 6 padding\n}\nprint(MemoryLayout\u003CGoodLayout>.size)  \u002F\u002F 16 bytes\n```\n\n### Alignment\n\n```swift\n\u002F\u002F Query alignment\nprint(MemoryLayout\u003CDouble>.alignment)  \u002F\u002F 8\nprint(MemoryLayout\u003CInt32>.alignment)   \u002F\u002F 4\n\n\u002F\u002F Structs align to largest member\nstruct Mixed {\n    var int32: Int32   \u002F\u002F 4 bytes, 4-byte aligned\n    var double: Double \u002F\u002F 8 bytes, 8-byte aligned\n}\nprint(MemoryLayout\u003CMixed>.alignment)  \u002F\u002F 8 (largest member)\n```\n\n### Cache-Friendly Data Structures\n\n```swift\n\u002F\u002F ❌ Poor cache locality\nstruct PointerBased {\n    var next: UnsafeMutablePointer\u003CNode>?  \u002F\u002F Pointer chasing\n}\n\n\u002F\u002F ✅ Array-based for cache locality\nstruct ArrayBased {\n    var data: ContiguousArray\u003CInt>  \u002F\u002F Contiguous memory\n}\n\n\u002F\u002F Array iteration ~10x faster due to cache prefetching\n```\n\n### Exclusivity Checks\n\nFrom WWDC 2025-312: Runtime exclusivity enforcement (`swift_beginAccess`\u002F`swift_endAccess`) appears in Time Profiler when the compiler cannot prove memory safety statically.\n\n**What they are**: Swift enforces that no two accesses to the same variable overlap if one is a write. For struct properties, this is checked at compile time. For class stored properties, runtime checks are inserted.\n\n**How to identify**: Look for `swift_beginAccess` and `swift_endAccess` in Time Profiler or Processor Trace flame graphs.\n\n```swift\n\u002F\u002F ❌ Class properties require runtime exclusivity checks\nclass Parser {\n    var state: ParserState\n    var cache: [Int: Pixel]\n\n    func parse() {\n        state.advance()         \u002F\u002F swift_beginAccess \u002F swift_endAccess\n        cache[key] = pixel      \u002F\u002F swift_beginAccess \u002F swift_endAccess\n    }\n}\n\n\u002F\u002F ✅ Struct properties checked at compile time — zero runtime cost\nstruct Parser {\n    var state: ParserState\n    var cache: InlineArray\u003C64, Pixel>\n\n    mutating func parse() {\n        state.advance()         \u002F\u002F No runtime check\n        cache[key] = pixel      \u002F\u002F No runtime check\n    }\n}\n```\n\n**Real-world impact**: In WWDC 2025-312's QOI image parser, moving properties from a class to a struct eliminated all runtime exclusivity checks, contributing to a measurable speedup as part of a >700x total improvement.\n\n---\n\n## Part 10: Typed Throws (Swift 6)\n\nTyped throws can be faster than untyped by avoiding existential overhead.\n\n### Untyped vs Typed\n\n```swift\n\u002F\u002F Untyped - existential container for error\nfunc fetchData() throws -> Data {\n    \u002F\u002F Can throw any Error\n    throw NetworkError.timeout\n}\n\n\u002F\u002F Typed - concrete error type\nfunc fetchData() throws(NetworkError) -> Data {\n    \u002F\u002F Can only throw NetworkError\n    throw NetworkError.timeout\n}\n```\n\n### Performance Impact\n\n```swift\n\u002F\u002F Measure with tight loop\nfunc untypedThrows() throws -> Int {\n    throw GenericError.failed\n}\n\nfunc typedThrows() throws(GenericError) -> Int {\n    throw GenericError.failed\n}\n\n\u002F\u002F Benchmark: typed ~5-10% faster (no existential overhead)\n```\n\n### When to Use\n\n- **Typed**: Library code with well-defined error types, hot paths\n- **Untyped**: Application code, error types unknown at compile time\n\n---\n\n## Part 11: Span Types\n\n**Swift 6.2+** introduces Span—a non-escapable, non-owning view into memory that provides safe, efficient access to contiguous data.\n\n### What is Span?\n\nSpan is a modern replacement for `UnsafeBufferPointer` that provides:\n- **Spatial safety**: Bounds-checked operations prevent out-of-bounds access\n- **Temporal safety**: Lifetime inherited from source, preventing use-after-free\n- **Zero overhead**: No heap allocation, no reference counting\n- **Non-escapable**: Cannot outlive the data it references\n\n```swift\n\u002F\u002F Traditional unsafe approach\nfunc processUnsafe(_ data: UnsafeMutableBufferPointer\u003CUInt8>) {\n    data[100] = 0  \u002F\u002F Crashes if out of bounds!\n}\n\n\u002F\u002F Safe Span approach\nfunc processSafe(_ data: MutableSpan\u003CUInt8>) {\n    data[100] = 0  \u002F\u002F Traps with clear error if out of bounds\n}\n```\n\n### When to Use Span vs Array vs UnsafeBufferPointer\n\n| Use Case | Recommendation |\n|----------|---------------|\n| **Own the data** | Array (full ownership, COW) |\n| **Temporary view for reading** | Span (safe, fast) |\n| **Temporary view for writing** | MutableSpan (safe, fast) |\n| **C interop, performance-critical** | RawSpan (untyped bytes) |\n| **Unsafe performance** | UnsafeBufferPointer (legacy, avoid) |\n\n### Basic Span Usage\n\n```swift\nlet array = [1, 2, 3, 4, 5]\nlet span = array.span        \u002F\u002F Read-only view\nprint(span[0])               \u002F\u002F Subscript access\nfor element in span { }      \u002F\u002F Safe iteration\nlet slice = span[1..\u003C3]      \u002F\u002F Span slice, no copy\n```\n\n### MutableSpan for Modifications\n\n```swift\nvar array = [10, 20, 30, 40, 50]\nlet mutableSpan = array.mutableSpan\nmutableSpan[0] = 100  \u002F\u002F Modifies array in-place, bounds-checked\n```\n\n### RawSpan for Untyped Bytes\n\n```swift\nfunc parsePacket(_ data: RawSpan) -> PacketHeader? {\n    guard data.count >= MemoryLayout\u003CPacketHeader>.size else { return nil }\n    \u002F\u002F Safe byte-level access via subscript\n    return PacketHeader(version: data[0], flags: data[1],\n        length: UInt16(data[3]) \u003C\u003C 8 | UInt16(data[2]))\n}\n\nlet header = parsePacket(bytes.rawSpan)  \u002F\u002F .rawSpan on any [UInt8]\n```\n\nAll Swift 6.2 collections provide `.span` and `.mutableSpan` properties, including `Array`, `ContiguousArray`, and `UnsafeBufferPointer` (migration path). Span access speed matches `UnsafeBufferPointer` (~2ns) with bounds checking.\n\n### Non-Escapable Lifetime Safety\n\nSpan's lifetime is bound to its source. The compiler prevents returning a Span from a function where the source would be deallocated — unlike `UnsafeBufferPointer`, which allows this bug silently.\n\n```swift\nfunc dangerousSpan() -> Span\u003CInt> {\n    let array = [1, 2, 3]\n    return array.span  \u002F\u002F ❌ Error: Cannot return non-escapable value\n}\n```\n\nInlineArray also provides `.span`\u002F`.mutableSpan` — see Part 7 for InlineArray usage and copy-avoidance via Span.\n\n### Migration from UnsafeBufferPointer\n\n```swift\n\u002F\u002F ❌ Old: unsafe, no bounds checking\nfunc parseLegacy(_ buffer: UnsafeBufferPointer\u003CUInt8>) -> Header {\n    Header(magic: buffer[0], version: buffer[1])  \u002F\u002F Silent OOB crash\n}\n\n\u002F\u002F ✅ New: safe, bounds-checked, same performance\nfunc parseModern(_ span: Span\u003CUInt8>) -> Header {\n    Header(magic: span[0], version: span[1])  \u002F\u002F Traps on OOB\n}\n\n\u002F\u002F Bridge: existing UnsafeBufferPointer → Span\nlet span = buffer.span  \u002F\u002F Wrap unsafe in safe span\nparseModern(span)\n```\n\n### OutputSpan — Safe Initialization\n\nOutputSpan\u002FOutputRawSpan replace `UnsafeMutableBufferPointer` for initializing new collections without intermediate allocations.\n\n```swift\n\u002F\u002F Binary serialization: write header bytes safely\n@lifetime(&output)\nfunc writeHeader(to output: inout OutputRawSpan) {\n    output.append(0x01)       \u002F\u002F version\n    output.append(0x00)       \u002F\u002F flags\n    output.append(UInt16(42)) \u002F\u002F length (type-safe)\n}\n```\n\nUse for building byte arrays, binary serialization, image pixel data. Apple's open-source [Swift Binary Parsing](https:\u002F\u002Fgithub.com\u002Fapple\u002Fswift-binary-parsing) library is built entirely on Span types.\n\n### When NOT to Use Span\n\n- **Ownership**: Span can't be stored in structs\u002Fclasses — use Array for owned data, provide `.span` access via computed property\n- **Return values**: Span is non-escapable — process in scope, return owned data\n- **Long-lived references**: Span lifetime is bound to source — use Array if data must outlive the current scope\n\n---\n\n## Copy-Paste Patterns\n\n### Pattern 1: COW Wrapper\n\n```swift\nfinal class Storage\u003CT> {\n    var value: T\n    init(_ value: T) { self.value = value }\n}\n\nstruct COWWrapper\u003CT> {\n    private var storage: Storage\u003CT>\n\n    init(_ value: T) {\n        storage = Storage(value)\n    }\n\n    var value: T {\n        get { storage.value }\n        set {\n            if !isKnownUniquelyReferenced(&storage) {\n                storage = Storage(newValue)\n            } else {\n                storage.value = newValue\n            }\n        }\n    }\n}\n```\n\n### Pattern 2: Performance-Critical Loop\n\n```swift\nfunc processLargeArray(_ input: [Int]) -> [Int] {\n    var result = ContiguousArray\u003CInt>()\n    result.reserveCapacity(input.count)\n\n    for element in input {\n        result.append(transform(element))\n    }\n\n    return Array(result)\n}\n```\n\n### Pattern 3: Inline Cache Lookup\n\n```swift\nprivate var cache: [Key: Value] = [:]\n\n@inlinable\nfunc getCached(_ key: Key) -> Value? {\n    return cache[key]  \u002F\u002F Inlined across modules\n}\n```\n\n---\n\n## Anti-Patterns\n\n| Anti-Pattern | Problem | Fix |\n|---|---|---|\n| **Premature optimization** | Complex COW\u002FContiguousArray with no profiling data | Start simple, profile, optimize what matters |\n| **Weak everywhere** | `weak` on every delegate (atomic overhead) | Use `unowned` when lifetime is guaranteed (see Part 4) |\n| **Actor for everything** | Actor isolation on simple counters (~100μs\u002Fcall) | Use lock-free atomics (`ManagedAtomic`) for simple sync data |\n\n---\n\n## Code Review Checklist\n\n### Memory Management\n- [ ] Large structs (>64 bytes) use indirect storage or are classes\n- [ ] COW types use `isKnownUniquelyReferenced` before mutation\n- [ ] Collections use `reserveCapacity` when size is known\n- [ ] Weak references only where needed (prefer unowned when safe)\n\n### Generics\n- [ ] Protocol types use `some` instead of `any` where possible\n- [ ] Hot paths use concrete types or `@_specialize`\n- [ ] Generic constraints are as specific as possible\n\n### Collections\n- [ ] Pure Swift code uses `ContiguousArray` over `Array`\n- [ ] Dictionary keys have efficient `hash(into:)` implementations\n- [ ] Lazy evaluation used for short-circuit operations\n\n### Concurrency\n- [ ] Synchronous operations don't use `async`\n- [ ] Actor calls are batched when possible\n- [ ] Task creation is minimized (use TaskGroup)\n- [ ] CPU-intensive work uses `@concurrent` (Swift 6.2)\n\n### Optimization\n- [ ] Profiling data exists before optimization\n- [ ] Inlining only for small, frequently called functions\n- [ ] Memory layout optimized for cache locality (large structs)\n\n---\n\n## Pressure Scenarios\n\n### Scenario 1: \"Just make it faster, we ship tomorrow\"\n\n**The Pressure**: Manager sees \"slow\" in profiler, demands immediate action.\n\n**Red Flags**:\n- No baseline measurements\n- No Time Profiler data showing hotspots\n- \"Make everything faster\" without targets\n\n**Time Cost Comparison**:\n- Premature optimization: 2 days of work, no measurable improvement\n- Profile-guided optimization: 2 hours profiling + 4 hours fixing actual bottleneck = 40% faster\n\n**How to Push Back Professionally**:\n```\n\"I want to optimize effectively. Let me spend 30 minutes with Instruments\nto find the actual bottleneck. This prevents wasting time on code that's\nnot the problem. I've seen this save days of work.\"\n```\n\n### Scenario 2: \"Use actors everywhere for thread safety\"\n\n**The Pressure**: Team adopts Swift 6, decides \"everything should be an actor.\"\n\n**Red Flags**:\n- Actor for simple value types\n- Actor for synchronous-only operations\n- Async overhead in tight loops\n\n**Time Cost Comparison**:\n- Actor everywhere: 100μs overhead per operation, janky UI\n- Appropriate isolation: 10μs overhead, smooth 60fps\n\n**How to Push Back Professionally**:\n```\n\"Actors are great for isolation, but they add overhead. For this simple\ncounter, lock-free atomics are 10x faster. Let's use actors where we need\nthem—shared mutable state—and avoid them for pure value types.\"\n```\n\n### Scenario 3: \"Inline everything for speed\"\n\n**The Pressure**: Someone reads that inlining is faster, marks everything `@inlinable`.\n\n**Red Flags**:\n- Large functions marked `@inlinable`\n- Internal implementation details exposed\n- Binary size increases 50%\n\n**Time Cost Comparison**:\n- Inline everything: Code bloat, slower app launch (3s → 5s)\n- Selective inlining: Fast launch, actual hotspots optimized\n\n**How to Push Back Professionally**:\n```\n\"Inlining trades code size for speed. The compiler already inlines when\nbeneficial. Manual @inlinable should be for small, frequently called\nfunctions. Let's profile and inline the 3 actual hotspots, not everything.\"\n```\n\n---\n\n## Real-World Examples\n\n### Example 1: Image Processing Pipeline\n\n**Problem**: Processing 1000 images takes 30 seconds.\n\n**Investigation**:\n```swift\n\u002F\u002F Original code\nfunc processImages(_ images: [UIImage]) -> [ProcessedImage] {\n    var results: [ProcessedImage] = []\n    for image in images {\n        results.append(expensiveProcess(image))  \u002F\u002F Reallocations!\n    }\n    return results\n}\n```\n\n**Solution**:\n```swift\nfunc processImages(_ images: [UIImage]) -> [ProcessedImage] {\n    var results = ContiguousArray\u003CProcessedImage>()\n    results.reserveCapacity(images.count)  \u002F\u002F Single allocation\n\n    for image in images {\n        results.append(expensiveProcess(image))\n    }\n\n    return Array(results)\n}\n```\n\n**Result**: 30s → 8s (73% faster) by eliminating reallocations.\n\n### Example 2: Generic Specialization\n\n**Problem**: Protocol-based rendering is slow.\n\n**Investigation**:\n```swift\n\u002F\u002F Original - existential overhead\nfunc render(shapes: [any Shape]) {\n    for shape in shapes {\n        shape.draw()  \u002F\u002F Dynamic dispatch\n    }\n}\n```\n\n**Solution**:\n```swift\n\u002F\u002F Specialized generic\nfunc render\u003CS: Shape>(shapes: [S]) {\n    for shape in shapes {\n        shape.draw()  \u002F\u002F Static dispatch after specialization\n    }\n}\n\n\u002F\u002F Or use @_specialize\n@_specialize(where S == Circle)\n@_specialize(where S == Rectangle)\nfunc render\u003CS: Shape>(shapes: [S]) { }\n```\n\n**Result**: 100ms → 10ms (10x faster) by eliminating witness table overhead.\n\n---\n\n## Resources\n\n**WWDC**: 2025-312, 2024-10217, 2024-10170, 2021-10216, 2016-416\n\n**Docs**: \u002Fswift\u002Finlinearray, \u002Fswift\u002Fspan, \u002Fswift\u002Foutputspan\n\n**Skills**: axiom-performance-profiling, axiom-swift-concurrency, axiom-swiftui-performance\n\n---\n\n",{"name":5,"license":15,"metadata":34,"description":7},{"version":35},"1.2.0","main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-swift-performance",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill axiom-swift-performance",{"tool":51,"command":52},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill axiom-swift-performance",{"tool":54,"command":55},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill axiom-swift-performance","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-swift-performance\u002FSKILL.md",true,[],[60,74,84,93,99,106],{"skillNo":61,"name":62,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":70,"publishedAt":29},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[65],{"categoryNo":66,"categoryName":67,"taxonomyType":68,"taxonomyTypeDesc":69},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[71,72,73],"model","model hierarchy","model hierarchy skill",{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":80,"publishedAt":29},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[79],{"categoryNo":66,"categoryName":67,"taxonomyType":68,"taxonomyTypeDesc":69},[81,82,83],"MCP","zoom","zoom mcp",{"skillNo":85,"name":86,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":29},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[90,91,92,82],"sdk","zoom apps sdk","apps",{"skillNo":94,"name":95,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":29},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[95],{"skillNo":100,"name":101,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":105,"publishedAt":29},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[104],{"categoryNo":66,"categoryName":67,"taxonomyType":68,"taxonomyTypeDesc":69},[101],{"skillNo":107,"name":108,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":29},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[108]]