3.4 · Object layout, side tables, tagged pointers
What a class instance, a struct and a weak reference physically are. Interviews reach this level to see whether you can reason about cost, not just correctness.
Mental model. Every class instance is a 16-byte header (type pointer plus reference counts) followed by its stored properties. Weak references, unowned counts and heap allocations all hang off that header.
Size and placement
How big things are, and what lands on the heap.
- What does a class instance look like in memory?
A Swift class instance is a heap block that starts with a 16-byte header: a pointer to the type’s metadata (which gives the runtime its class, vtable and… - What do MemoryLayout’s size, stride and alignment mean, and why does field order matter?
size is the number of bytes the value itself occupies. alignment is the address multiple it must sit on (often its largest field’s size). stride is the… - What actually allocates on the heap in Swift, and how do you see it?
Structs, enums and tuples are stored inline where they live (in a stack frame, in another object, in an array’s buffer) and need no allocation of their own.…
Under the reference counts
Side tables, weak registration and tagged pointers.
- What is a side table, and when does the runtime create one?
A native object’s second header word packs its strong count, unowned count and some flags (such as “is deinitialising”) into one 64-bit value, so retain and… - How does a weak reference get zeroed when the object dies?
Two mechanisms exist, depending on the object. For native Swift objects the side table (see above) records the weak count and the object’s state. A weak… - What is a tagged pointer, and what other tricks avoid allocating?
A tagged pointer stores a small value inside the pointer bits instead of allocating an object. Objective-C uses them for small NSNumber values, short NSStrings…
More in Memory, ARC & runtime
- 3.1 · ARC, autorelease pools, object lifetime
- 3.2 · strong, weak, unowned, unowned(unsafe)
- 3.3 · Cycles: delegates, closures, timers, Combine, tasks
- 3.5 · The copy-on-write mechanism
- 3.6 · Retain traffic, parameter conventions, Unmanaged, bridging
- 3.7 · Leaks, abandoned memory, footprint, and the tools
- 3.8 · deinit rules, process exit, isolated deinit, noncopyable types and consume
- 3.9 · Weak collections, nested closures, structs holding references, weak let and escaped pointers
- 3.10 · Enum layout, existential boxing, tail allocation, slice retention, growth and the command-line tools