In Swift, which values need a heap allocation instead of the stack, and when can the optimizer keep a class instance on the stack?
answer
- storage follows the container
- class instances and their counts
- escaping closures box captured vars
- indirect cases, oversized existentials
- never escapes, so stack-promoted
basics
~20 sClass instances, escaping-closure contexts and the vars they capture, indirect enum payloads, collection buffers and oversized existentials are heap-allocated; a struct is stored inline wherever it lives. Under -O, a class instance that never escapes can be stack-promoted.
solid answer
~40 sA struct or enum has no home of its own: it is stored inline in whatever holds it, a local's stack slot or registers, a class instance's heap storage, or an array's heap buffer. The heap gets class instances, the context of an escaping closure, a box for each `var` an escaping closure captures, the payload of an `indirect` enum case, the storage behind `Array`, `Dictionary` and longer `String`s, and an existential's value when it does not fit the three-word inline buffer. Under `-O` the optimizer can **stack-promote** a class instance it proves never escapes the function, and a closure that does not escape needs no box for the variables it captures. The Allocations instrument shows which of these a hot path actually pays for.
code
swift · 25 linesfinal class Cursor {
var offset = 0
}
@inline(never)
func advance(_ c: Cursor) { c.offset += 1 }
public func localCursor(_ n: Int) -> Int {
let c = Cursor() // -O: stack-promoted, it never escapes
for _ in 0..<n { advance(c) }
return c.offset
}
public func escapingCounter(_ handlers: inout [() -> Void]) -> Int {
var hits = 0 // heap box: an escaping closure captures it
handlers.append { hits += 1 }
handlers.forEach { $0() }
return hits
}
public func nonEscapingCounter(_ xs: [Int]) -> Int {
var hits = 0 // no box: forEach's closure does not escape
xs.forEach { if $0 > 0 { hits += 1 } }
return hits
}go deeper
Recall that class instances are heap-allocated and reference-counted, while a struct is stored inline in whatever holds it rather than always on the stack.
Walk through the heap cases one by one: escaping closure contexts, boxed captured vars, indirect payloads, collection buffers, large existentials. Then explain when stack promotion removes a class allocation.
Show how you would find and remove allocations in a Release profile with the Allocations instrument, and why escape and callee visibility decide whether the optimizer can help.
Weigh the API cost of avoiding allocations, such as non-escaping callbacks, trivial value types and flat storage, against readability, and limit that discipline to modules a profile proves hot.
## Values are stored where they live The interview shortcut "structs on the stack, classes on the heap" is half right. A **value type** (struct, enum, tuple) is stored **inline**: its bytes sit directly inside whatever contains it. - A local `let` or `var` of struct type lives in the function's stack frame or in registers. - The same struct stored as a property of a class instance lives inside that instance's **heap** allocation. - An `Array` of that struct keeps every element inline in the array's heap buffer, contiguously. - A struct that contains a `String` or an `Array` is inline itself, but those fields point at heap buffers of their own (short strings, up to 15 UTF-8 bytes on 64-bit Apple platforms, are stored inline instead). So the useful question is not "struct or class?" but "which constructs force a separate heap allocation, with its reference count, and can the optimizer avoid it?" ## What allocates on the heap | Construct | What is allocated | Why | |---|---|---| | Class instance | The object, with a reference count | References can be shared and outlive the creating scope | | Escaping closure | Its capture context | The closure can run after the function returns | | `var` captured by an escaping closure | A heap **box** for that variable | Creator and closure must read and write the same storage | | `indirect` enum case | A box for the payload | A recursive enum would otherwise have infinite size | | `Array`, `Dictionary`, `Set`, longer `String` | The element storage buffer | Size is only known at run time | | Existential (`any P`) holding a large value | A side allocation | The inline buffer is three pointers wide; larger values go out of line | Two rows deserve precision. A captured `let` is copied by value into the closure's context, so it needs no box of its own; only a captured `var` gets one, because both sides must see later writes. And existential boxing belongs to the lesson on opaque and existential types; here it matters only as one more source of allocations in a profile. ## Stack promotion of class instances Allocating a class instance normally calls into the runtime, initializes a reference count and later frees the memory. With optimization on, the compiler's **stack promotion** can place the instance in the stack frame instead, when it proves that no reference to the object outlives the function. In Swift Intermediate Language (SIL), the compiler's internal representation, this shows up as `alloc_ref [stack]` instead of a plain heap `alloc_ref`. What the optimizer needs: 1. **Optimization enabled.** At `-Onone` the same code calls the class's heap-allocating initializer. 2. **No escape.** The reference must not be stored in a property, a global, a collection or an escaping closure, or be returned. 3. **Visible callees.** If the instance is passed to a function whose body the optimizer cannot see, such as a non-inlinable function in another module, it must assume the callee might keep the reference. Stack promotion is an optimization, not a language guarantee: do not design an API around it, but do not be surprised when a small helper object disappears from the Allocations instrument in a Release build. ## Closures and captured variables Whether a closure escapes decides its cost. A closure passed to `Array.forEach` or `map` is non-escaping, so it can use the caller's variables directly and nothing is boxed. Storing a closure in an array, a property or a completion handler makes it escaping: whatever it captures goes into a heap-allocated context, and every captured `var` gets its own box. The compiler's own optimization tips recommend passing a variable `inout` to a helper instead of capturing it in an escaping closure that is only used locally. ## Finding the allocations In a JSON-parsing hot path, the common offenders are a class allocated per token, escaping callbacks per element and arrays rebuilt per object. To find them: 1. Profile a Release build with the Allocations instrument and sort by count of transient allocations. 2. Inspect the call stacks of the largest categories to see which of your functions allocate. 3. Rebuild with the Swift 6.4 compiler's opt-in `PerformanceHints` warning group (`-Wwarning PerformanceHints`), which flags existential types, functions returning `Array` or `Dictionary`, and untyped `throws`, each of which can heap-allocate. 4. Replace per-token objects with plain structs in one contiguous array, and keep callbacks non-escaping where the API allows.
- Does making a model a struct guarantee that a hot loop over it makes no heap allocations?No. The struct itself is inline, but a `String` or `Array` field usually points at a heap buffer that copying the struct retains, a protocol-typed field may box a large value, and growing an array reallocates its storage. A struct whose fields are all trivial, such as integers and fixed-size tuples of them, avoids both allocation and reference counting.
- How can the compiler point out allocation-prone constructs before you profile?The Swift 6.4 compiler has an opt-in `PerformanceHints` diagnostic group, off by default. Pass `-Wwarning PerformanceHints`, or `-Werror PerformanceHints` to fail the build, and it warns on existential types, functions or closures returning `Array` or `Dictionary`, and untyped `throws`. Treat the warnings as hints for performance-critical modules, not as rules for every file.
- Why can a class instance be stack-promoted in one function but not after you pass it to a function in another module?Stack promotion needs proof that no reference outlives the function. When the callee's body is visible, the optimizer can check that it neither stores nor returns the reference. A non-inlinable function in a separately compiled module is opaque, so the optimizer must assume it might keep the reference, and the instance stays on the heap.
- Structs always live on the stack and classes always on the heap.
- A let captured by an escaping closure needs its own heap box, just like a var.
- Swift never places a class instance on the stack.
- Closures passed to forEach or map box every variable they capture.
- An indirect enum case is stored inline like any other case.
Assumes Swift 6.4 for the opt-in PerformanceHints warning group; the allocation rules themselves hold in every supported release.