Memory Hierarchy
Registers, caches, DRAM, SSDs and disks — why memory is layered, the principle of locality, and how to write cache-friendly code.
We want memory that is fast, large and cheap. No single technology is all three, so computers stack several: small, fast and expensive at the top; large, slow and cheap at the bottom. Thanks to locality, the illusion works: most accesses hit the fast levels.
The principle of locality
- Temporal locality — something used recently is likely to be used again soon (loop variables, hot functions).
- Spatial locality — data near something just used is likely to be used soon (array elements, sequential instructions).
Caches exploit both: they keep recently used data, and they fetch a whole cache line (64 bytes on most CPUs) at a time, not just the byte you asked for.
Average memory access time
With a 1 ns L1, a 5% miss rate and a 100 ns penalty: AMAT = 1 + 0.05 × 100 = 6 ns — six times slower than a perfect L1. With a 1% miss rate it's 2 ns. Small changes in miss rate matter a lot.
Cache-friendly code
Traverse arrays in memory order
2-D arrays in C, Java (an array of row arrays), and NumPy (by default) are row-major: each row is contiguous.
// Fast: walks memory sequentially (row by row)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
sum += a[i][j];
// Slow (often 5-10x for large n): jumps a whole row between accesses
for (int j = 0; j < n; j++)
for (int i = 0; i < n; i++)
sum += a[i][j];import numpy as np
a = np.random.rand(5000, 5000) # row-major (C order)
a.sum(axis=1) # contiguous rows: fast
a.T.copy() # transposing touches memory in a strided pattern: slower
# np.asfortranarray gives column-major layout when you need column access// Typed arrays are contiguous; a flat array with manual indexing beats
// an array of arrays for numeric work.
const a = new Float64Array(n * n);
for (let i = 0; i < n; i++)
for (let j = 0; j < n; j++)
sum += a[i * n + j]; // row-major traversalPrefer contiguous data structures
- An array of values is contiguous; a linked list scatters nodes around the heap, so each
nextmay be a cache miss. This is whyArrayListusually beatsLinkedList, even for insertions in the middle of small lists. - In Java, a
List<Integer>holds pointers to boxed objects; anint[]holds the numbers themselves. - Structure of arrays (SoA) vs array of structures (AoS): if a loop only reads
xfrom each particle, storing all thexvalues together means each cache line contains only useful data. Game engines and ECS architectures rely on this.
Block (tile) large computations
Matrix multiplication on big matrices touches far more data than fits in the cache. Tiling processes sub-blocks that fit in the cache, reusing each loaded value many times. Libraries like BLAS do this, which is why they're 10–100× faster than a naive triple loop.
Bandwidth vs latency
- Latency — how long one access takes (~100 ns to DRAM).
- Bandwidth — how many bytes per second you can stream (~50–100 GB/s per socket of DDR5).
Sequential access is fast because hardware prefetchers detect the pattern and fetch ahead, hiding latency. Random access (hash tables, pointer chasing, graph traversal) is limited by latency.
Storage levels
| SSD (NVMe) | HDD | |
|---|---|---|
| Random read | ~20–100 µs | ~5–10 ms (seek + rotation) |
| Sequential | 3–14 GB/s | ~200 MB/s |
| Unit of access | Pages (4–16 KB); erase blocks (MBs) | Sectors (512 B–4 KB) |
The OS uses free RAM as a page cache for file data, so repeated reads of the same file come from memory. Databases are designed around these numbers (Storage engines).
- The hierarchy trades speed for size and cost; locality makes it work.
- Caches move 64-byte lines, exploiting spatial locality.
- AMAT = hit time + miss rate × miss penalty; small miss-rate changes matter.
- Write cache-friendly code: sequential traversal, contiguous structures, tiling.
- Sequential access is bandwidth-bound and prefetchable; random access is latency-bound.
QWhy is iterating over an ArrayList faster than over a LinkedList even though both are O(n)?medium
The ArrayList's backing array is contiguous, so each cache line brings in several references and the prefetcher streams ahead. LinkedList nodes are scattered across the heap, so each step can be a cache miss costing ~100 ns. Big-O hides constant factors that differ by 10× or more.