Heap vs Stack

The interviewer asks

“What's the difference between heap and stack allocation?”

How to answer

The stack is per-thread memory for function frames: allocating is just moving the stack pointer, it's freed automatically when the function returns, and it's small (on the order of 1 MB for the main thread and less for secondary threads). The heap is shared, dynamically sized memory: allocating means finding a free block (with synchronization), and objects need reference counting to know when to free them, so it's much more expensive. In Swift, class instances live on the heap; value types are stored inline wherever their container is: in a stack frame for a local, but inside a heap object if they're a property of a class, an array element, a captured variable, or boxed in an existential. So "structs are on the stack" is a simplification; the real rule is "value types avoid their own heap allocation and reference counting".

Key points

  • Stack: LIFO, per thread, fast, fixed size, lifetime tied to scope
  • Heap: shared, flexible lifetime, malloc/free + atomic retain/release (ARC)
  • Classes, actors and closures' captured context: heap (the optimizer can promote non-escaping objects to the stack)
  • Value types: inline in their container; collections (Array, String, Dictionary) are small structs pointing to a heap buffer
  • Existentials (any P) store values up to 3 words inline and box larger ones on the heap; some P/generics avoid the box
  • Swift 6.2: InlineArray (fixed size, no heap buffer) and Span (safe, non-escaping view) avoid heap buffers and copies; ~Copyable types avoid copies and give unique ownership

If they dig deeper

Why heap is slower: allocator work, cache misses from pointer chasing, and atomic reference-count traffic, often more than the allocation itself. Large structs are fine on the stack but cost on every copy, and copying many large values can be worse than sharing a class; COW collections give both. Deep recursion or a huge local InlineArray can overflow the stack (EXC_BAD_ACCESS on the guard page). Span is ~Escapable: the compiler guarantees it can't outlive the memory it views, which is what makes it a safe replacement for withUnsafeBufferPointer. Find heap hotspots with the Allocations instrument (allocation counts, not just bytes) and Time Profiler (swift_allocObject, swift_retain/swift_release).

Common pitfalls

Saying all structs live on the stack or that structs are always faster. Making a type a struct while it holds many class references (each copy retains them all). Ignoring existential boxing in hot paths. Quoting a fixed stack size as a guarantee. Using InlineArray for large or variable data.

How to use it

swift
struct Point { var x: Double, y: Double }   // 16 bytes, stored inline wherever it lives
struct Matrix2x2 { var a, b, c, d: Double }  // 32 bytes
final class Node { var value = 0 }          // always a heap object (unless the optimizer proves it doesn't escape)

final class Scene {
    var origin = Point(x: 0, y: 0)          // inline inside the Scene heap object, so on the heap
}

func allocations() {
    let p = Point(x: 1, y: 2)               // stack (or registers): no malloc, no ARC
    let n = Node()                          // heap: malloc + reference counting
    let points = [p, p, p]                  // the Array value is a pointer; elements live in a heap buffer
    let boxed: any Sendable = Matrix2x2(a: 1, b: 0, c: 0, d: 1)  // > 3 words: existential boxes it on the heap
    var counter = 0
    let increment = { counter += 1 }        // a captured var may be boxed on the heap
    increment()
    _ = (n, points, boxed)
}

// Swift 6.2: fixed-size storage with no heap buffer
func sumOfSquares() -> Int {
    var squares: InlineArray<8, Int> = .init(repeating: 0)   // 64 bytes inline (on the stack here)
    for i in squares.indices { squares[i] = i * i }
    let view: Span<Int> = squares.span                      // safe, non-escaping view; no copy
    var total = 0
    for i in view.indices { total += view[i] }
    return total
}

Best practices

  • Prefer value types for data models; use classes for identity, shared mutable state, and lifetimes
  • Avoid needless heap traffic in hot loops: existentials, captured vars, temporary arrays
  • Use some/generics over any where performance matters
  • Adopt InlineArray/Span (Swift 6.2) for small fixed-size buffers and safe views; ~Copyable for unique resources
  • Measure allocation counts with Allocations before restructuring code

Related concepts

  • Value vs reference types, ARC, copy-on-write, noncopyable types, existentials (any vs some), compiler optimizations, Allocations instrument, address sanitizer