Memory Hierarchy and Caches
Understand registers, caches, RAM and disk, cache mapping and replacement, locality, and how to write cache-friendly code.
Intermediate · about 4 hours · difficulty 3/5
Learn first: CPU Organisation, Instructions and Pipelining, Memory Management and Virtual Memory
Memory is a hierarchy of trade-offs: small and fast near the CPU, large and slow far away. Knowing the rough numbers changes how you write code and how you reason in system design.
The hierarchy
Registers (under 1 ns), L1 cache (about 1 ns), L2 and L3 (a few to tens of ns), main memory (about 100 ns), SSD (tens to hundreds of microseconds), HDD (milliseconds), network round trips (up to hundreds of ms). Each level caches the one below.
Locality
- Temporal locality: data used recently will likely be used again.
- Spatial locality: data near recently used data will likely be used soon. Caches fetch whole cache lines (often 64 bytes) to exploit this.
- Iterating a 2D array row by row in C++ is much faster than column by column because rows are contiguous.
- Arrays beat linked lists in practice partly because of spatial locality, even when Big-O is equal.
Cache organisation
- Direct mapped: each block maps to exactly one line (simple, conflict misses).
- Fully associative: any block anywhere (flexible, expensive).
- Set associative: a compromise, used in real CPUs.
- Address split into tag, index and offset; numericals ask for bit counts.
- Miss types: compulsory, capacity, conflict (the three Cs).
- Write-through vs write-back and write-allocate policies.
- Average memory access time = hit time + miss rate x miss penalty.
- Multicore cache coherence (MESI) and false sharing (optional).
Connecting ideas
The same concepts reappear everywhere: TLBs in OS, buffer pools in databases, CDNs and Redis in system design. LRU from page replacement is the same LRU cache you implement in DSA.
Good enough to move on: you can compute tag/index/offset bits for a set-associative cache, explain why row-major traversal is faster, and quote the rough latency ladder.
Key concepts
- Latency numbers and the hierarchy
- Temporal and spatial locality
- Cache lines
- Direct, associative and set-associative mapping
- Tag, index and offset numericals
- Write-through vs write-back
- Average memory access time
- Cache coherence and false sharing
Mini project
Benchmark summing a 4000 x 4000 matrix row-wise vs column-wise, and a vector vs a linked list of 10 million integers, then explain the timing differences in terms of cache lines and locality.
Check yourself
Why can iterating over a linked list be several times slower than an array even though both are O(n)?
Free resources
- Latency Numbers Every Programmer Should Know (Colin Scott)
- MIT 6.004 Computation Structures (MIT OCW)