What is a tagged pointer, and what other tricks avoid allocating?

3.4.6 · L5 · Learning

Predict first

Does retain or release on a tagged pointer cost an atomic operation?

// A: yes, like any object
// B: no, there is no object to count
  • A
  • B

Mental model. A parcel so small that the address label is the whole message. There is nothing to deliver and nothing to track.

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 and NSDates: the “pointer” is really data, so there is no memory block and retain and release do nothing. Code that inspects such a value’s address or treats it as a real object is wrong, and they never show up as leaks.

The same idea appears in several places. Swift’s String stores up to 15 UTF-8 bytes inline in its 16-byte value (the small-string optimisation). Optional of a class uses the null pointer for nil, so it costs no extra byte. Multi-payload enums stash their case in spare bits of the payload. All are ways to avoid heap traffic, which is why many tiny values never appear in Allocations.

The value lives in the pointer itself, so the runtime recognises the tag and returns without touching any memory.

Common traps

  • Comparing NSNumber objects with ===. Small ones may share or fake identity; use isEqual.
  • Looking for these values in the memory graph. They have no allocation, so there is nothing to see.

They might follow up with

  • Why does it matter in practice? Many small numbers and strings are cheap, and a million large ones are not. That is a boundary worth knowing when profiling.
  • Is this a Swift-only feature? No. Tagged pointers belong to the Objective-C runtime; Swift’s small strings and spare-bit enums are language-level equivalents.

Related questions

  • 3.4.3 What actually allocates on the heap in Swift, and how do you see it?
  • 3.4.4 What is a side table, and when does the runtime create one?

← How does a weak reference get zeroed when the object dies?