Memory
The memory hierarchy
The closer memory sits to the CPU, the faster and smaller it is:
- CPU registers — a few nanoseconds, a few dozen of them.
- L1/L2/L3 caches — invisible to the programmer, but they explain why a sequential pass over an
Arraybeats hopping through a linked list. - Main memory (RAM) — volatile: everything is lost when the process restarts. An iPhone has 6–12 GB and an app only gets a slice of it.
- Flash storage — long-term: the app bundle, Documents, Core Data/SwiftData, UserDefaults.
Stack and heap — what you will be asked about
Inside RAM a process has two regions that matter for Swift:
- Stack — one per thread (1 MB for the main thread on iOS, 512 KB by default for background threads). Allocation is a pointer bump, deallocation is automatic on function exit. Local variables and value types (
struct,enum) land here when the compiler can determine their size and lifetime. - Heap — shared by all threads, allocated with
malloc, freed by ARC. This is where everyclassinstance lives, plus the buffers ofArray/String/Dictionary, closures that captured variables, and value types that "escaped" (for example a struct stored inany Protocolthat doesn't fit the inline buffer).
struct Point { var x: Double; var y: Double } // a value — usually on the stack
final class Node { var next: Node? } // an object — always on the heap
func demo() {
let p = Point(x: 1, y: 2) // 16 bytes in the stack frame, gone on return
let n = Node() // malloc + refcount; dies when count == 0
var points = [p] // the array buffer is heap, though Array is a struct
points.append(Point(x: 3, y: 4))
_ = n
}
Why it matters on iOS
- The heap is more expensive: allocation, atomic
retain/release, possible races. That is why Apple recommends starting withstruct. - App memory is capped: past the limit the system sends
didReceiveMemoryWarning, then kills the process (jetsam). HenceNSCache, image downsampling, profiling in Instruments (Allocations, Leaks). - Deep recursion overflows the stack — an
EXC_BAD_ACCESScrash with no exception to catch.