Chapter Four · Memory and Its Hierarchy
Memory and Its Hierarchy
The cost model of Chapter 1 charged every memory read one step. This chapter replaces that flat memory with the real one, in six topics: the latency ladder the rest of the book cites, caches and locality, the stack and the heap, garbage collection, memory safety, and the cases where the ladder overrules Big-O.
A modern processor can do several hundred instructions' worth of work in the time it waits for one number from RAM. Most programs that feel slow on fast hardware spend their time waiting for memory, not computing. Whether a read costs one nanosecond or a hundred depends on where the data happens to be, and that depends on the order the program touches it, which the source code rarely makes obvious.
The chapter starts by building the latency ladder, from registers to a cross-continent round trip, as orders of magnitude with their sources. Later chapters cite it whenever they say "a cache miss" or "a round trip". It then shows how caches turn access order into speed, measured in Python as well as in theory, and follows memory through its life: handed out by an allocator, reclaimed by a collector, and misused when a language leaves reclamation to a person.
It ends where it was heading from the first page. Lantern's shortest postings lists are searched faster by a plain scan than by a tree with a better Big-O, and the reason is the ladder. The lesson is not that Big-O is wrong, but that it counts steps while the machine charges for distance.