Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

The Memory Hierarchy & Locality

Caches, cache lines and why scanning an array beats chasing pointers.

On an Apple M2 laptop, summing 2242^{24} integers stored in an array took a millisecond or two. Summing the same integers stored in a linked list whose nodes were shuffled through memory took about 1.8 seconds: roughly 106 nanoseconds per node, the time it takes to fetch one value from main memory. Both loops perform the same additions. The thousandfold gap is the memory hierarchy, and a cost model that ignores it cannot explain it.

What you’ll learn

  • Describe the memory hierarchy by orders of magnitude, and define cache lines, hits, misses, and spatial and temporal locality.
  • State the ideal-cache model, and justify its optimal replacement by the competitiveness of LRU.
  • Count the cache misses of scans, strided loops and pointer chasing, and explain why dependent misses cost even more than their number suggests.
  • Derive the Θ(n3/(BM))\Theta(n^3/(B\sqrt M)) cache complexity of tiled matrix multiplication, and prove the matching Hong–Kung lower bound with the Loomis–Whitney inequality.
  • Choose loop orders and data layouts (row or column order, structure of arrays, padding) for locality.

A hierarchy of memories

Fast memory is small and expensive; large memory is slow and cheap. So computers stack several levels, the memory hierarchy, and keep copies of recently used data in the small, fast levels, the caches. The numbers below are orders of magnitude only, since they vary between processors and generations:

LevelTypical sizeTime to fetch a value (order of magnitude)
registershundreds of bytespart of the instruction
L1 cachetens of KB per coreabout 1 ns: a few cycles
L2 cachehundreds of KB to a few MBa few ns
last-level (L3) cacheseveral to tens of MB, shared by the coresabout 10 ns: tens of cycles
main memory (DRAM)gigabytesabout 100 ns: hundreds of cycles
solid-state driveup to terabytestens of μs
hard diskterabytesmilliseconds
From L1 to DRAM the cost of a fetch grows about a hundredfold, and from DRAM to a hard disk about ten-thousandfold more. The 106 ns per shuffled node in the hook is one DRAM latency per node.

Locality is what makes caches work, and arrays have it built in: a scan uses every byte of every line it fetches, and its addresses are predictable, so the prefetcher hides most of the latency. A linked list scattered through memory has neither property. Worse, each node's address is known only after the previous node has arrived, so its misses cannot even overlap.

The ideal-cache model

Proof. NN contiguous words overlap at most ⌈N/B⌉+1\lceil N/B \rceil + 1 lines (one more when the block does not start at a line boundary), and a scan never returns to a line it has left, so each line is fetched once. Conversely, each miss brings in at most BB of the NN words.

Compare a linked list of NN nodes spread at random over a region much larger than MM: almost every hop lands on an uncached line, Θ(N)\Theta(N) misses, a factor of BB more. That factor even understates the damage. The scan's misses are independent: the processor keeps many in flight and the prefetcher runs ahead, so a scan is limited by memory bandwidth. Each pointer hop must wait for the previous load to learn its address, so the list pays the full latency, about 100 ns, for every node.

Predict before you look

An array of 10610^6 four-byte integers starts at a line boundary, and lines hold 64 bytes. How many cache lines does a full scan fetch?

Show the answer

62500

106×4=4×10610^6 \times 4 = 4 \times 10^6 bytes, and 4×106/64=62,5004 \times 10^6 / 64 = 62{,}500 lines: 16 integers per line, so only one access in 16 misses. With 128-byte lines it would be 31,250. Following 10610^6 shuffled list nodes instead can cost close to 10610^6 misses.

Loop order and tiling

Walk a row-major R×CR \times C matrix by rows and you scan it: about RC/BRC/B misses. Walk it by columns and consecutive accesses lie CC words apart. If the cache cannot hold one line for every row (R>M/BR > M/B), each line is evicted before the walk comes back for its next word, and every access misses: RCRC misses, BB times more.

Matrix multiplication, Cij+=AikBkjC_{ij} \mathrel{+}= A_{ik} B_{kj} in three nested loops over n×nn \times n row-major matrices, shows the same effect when nn is large:

  • in the order i,j,ki, j, k, the inner loop reads AA along a row but BB down a column: Θ(n3)\Theta(n^3) misses;
  • in the order i,k,ji, k, j, the inner loop reads rows of BB and CC: Θ(n3/B)\Theta(n^3/B) misses. In our test at n=1024n = 1024 this order ran about 8 times faster than i,j,ki, j, k;
  • tiling splits each matrix into t×tt \times t tiles and multiplies tile by tile, with tt chosen so that three tiles fit in the cache at once.
cpp
// C += A * B for n x n row-major matrices, tile by tile: 3 tiles (3t^2 numbers) live at once.
void matmul_tiled(int n, int t, const double* A, const double* B, double* C) {
    for (int i0 = 0; i0 < n; i0 += t)
        for (int k0 = 0; k0 < n; k0 += t)
            for (int j0 = 0; j0 < n; j0 += t)
                for (int i = i0; i < std::min(i0 + t, n); i++)
                    for (int k = k0; k < std::min(k0 + t, n); k++) {
                        double a = A[(size_t)i * n + k];
                        for (int j = j0; j < std::min(j0 + t, n); j++)
                            C[(size_t)i * n + j] += a * B[(size_t)k * n + j];
                    }
}

Needs <algorithm> and <cstddef>. Tuned linear-algebra libraries tile for the registers and for every cache level at once, and add vector instructions; whether this plain version beats the i,k,ji, k, j order on a given machine depends on those details. The point here is the number of misses.

DerivationTiled multiplication incurs Θ(n³/(B√M)) misses
  1. t=Θ(M),misses per tile product  ≤  3 t(tB+1)  =  O(t2B)t = \Theta(\sqrt M), \qquad \text{misses per tile product} \;\le\; 3\,t\Big(\frac{t}{B} + 1\Big) \;=\; O\Big(\frac{t^2}{B}\Big)

    Pick tt with 3t2≤M3t^2 \le M, so that one tile of each matrix fits, and assume t≥Bt \ge B, so that each row of a tile spans whole lines (a tall cache, M=Ω(B2)M = \Omega(B^2)). A tile has tt rows of tt words, each touching at most t/B+1t/B + 1 lines:

  2. Q(n;M,B)  =  (nt)3O(t2B)  =  O(n3tB)  =  O(n3BM)Q(n; M, B) \;=\; \Big(\frac{n}{t}\Big)^{3} O\Big(\frac{t^2}{B}\Big) \;=\; O\Big(\frac{n^3}{tB}\Big) \;=\; O\Big(\frac{n^3}{B\sqrt M}\Big)

    There are (n/t)3(n/t)^3 tile products, one for each triple of tile indices:

  3. n3/B n3/(BM)   =  M\frac{n^3/B}{\,n^3/(B\sqrt M)\,} \;=\; \sqrt M

    Compared with the i,k,ji, k, j order this saves a factor Θ(M)\Theta(\sqrt M): each number fetched is used about tt times before it is evicted.

DerivationProof sketch with the Loomis–Whitney inequality (Irony, Toledo & Tiskin, 2004)
  1. ∣A∣, ∣B∣, ∣C∣  ≤  2M\abs{\mathcal A},\ \abs{\mathcal B},\ \abs{\mathcal C} \;\le\; 2M

    Cut the execution into segments of MM word transfers each. During one segment, at most 2M2M entries of each matrix are available: up to MM already in fast memory, plus up to MM moved in or out.

  2. ∣S∣  ≤  ∣A∣ ∣B∣ ∣C∣  ≤  (2M)3/2\abs{S} \;\le\; \sqrt{\abs{\mathcal A}\,\abs{\mathcal B}\,\abs{\mathcal C}} \;\le\; (2M)^{3/2}

    The products computed in the segment form a set SS of triples (i,k,j)(i, k, j) whose projections lie in those sets: (i,k)(i, k) in A\mathcal A, (k,j)(k, j) in B\mathcal B and (i,j)(i, j) in C\mathcal C. The Loomis–Whitney inequality bounds a finite set of lattice points by its three projections:

  3. transfers  ≥  M(n3(2M)3/2−1)  =  n322 M−M  =  Ω(n3M)\text{transfers} \;\ge\; M\Big(\frac{n^3}{(2M)^{3/2}} - 1\Big) \;=\; \frac{n^3}{2\sqrt2\,\sqrt M} - M \;=\; \Omega\Big(\frac{n^3}{\sqrt M}\Big)

    All n3n^3 products must be formed, so there are at least n3/(2M)3/2n^3/(2M)^{3/2} segments, all but possibly the last with MM transfers each:

Layout: what lives next to what

Loop order is one half of locality; layout, the choice of which data share a line, is the other.

  • Structure of arrays. Records of 64 bytes stored one after another (an array of structures) occupy one 64-byte line each. A loop that reads only a 4-byte key still fetches every line: 16 times more data than it uses. Storing each field in its own array (a structure of arrays) packs 16 keys per line. In our test, summing 2222^{22} keys ran 14 to 25 times faster in the second layout, which also lets the compiler use vector instructions.
  • Allocation order. The linked list of the hook ran about 5 times slower than the array when its nodes sat in memory in list order, and about a thousand times slower when they were shuffled. Allocating nodes from a pool in traversal order recovers much of the gap; copying the data into a compact array before a hot loop recovers all of it.
  • Hot and cold fields. Moving rarely used fields out of a record packs more of the frequently used ones into each line.
  • Search trees. A binary search tree built from pointers misses at almost every level; packing nodes so that whole subtrees share a line or a disk block is the idea behind B-trees and behind the van Emde Boas layout of the next lesson.
Check your understanding

A program stores 10610^6 records of 64 bytes, each a 4-byte key followed by 60 bytes of payload, one after another in an array, and it repeatedly sums all the keys. Lines hold 64 bytes. Which change cuts its cache misses the most?

  1. Sort the records by key
  2. Store the keys in a separate array of their own
  3. Keep the records in a linked list instead
  4. Grow each record to 128 bytes, so that it fills a whole line on Apple's processors
Show the answer

B. Store the keys in a separate array of their own

The keys alone take 4×1064 \times 10^6 bytes, 62,500 lines, against 10610^6 lines when each key drags its 60-byte payload along: 16 times fewer misses per pass. Sorting changes the order of the keys, not the number of lines they occupy.

Many levels, and the frontier

A real machine has several levels, and the analysis applies to each adjacent pair with that pair's MM and BB: L1 and L2, the last-level cache and DRAM, DRAM and disk. The translation lookaside buffer, which caches address translations for pages of a few kilobytes (4 KB on most x86 systems, 16 KB on Apple's M-series), adds one more level for scattered access. A cache-aware algorithm tunes its tiles for every level, as optimized linear-algebra libraries do. A cache-oblivious algorithm never mentions MM or BB, and when its analysis holds for all MM and BB it is optimal at every level at once: the subject of the next lesson.

Think first Binary search on a sorted array of NN keys makes about log⁡2N\log_2 N probes. Roughly how many cache misses does it cost when the array is far larger than the cache?

About log⁡2N−log⁡2B=log⁡2(N/B)\log_2 N - \log_2 B = \log_2(N/B). The early probes jump across the whole array and each one misses; once the range has shrunk to a single line, the remaining log⁡2B\log_2 B probes hit. A B-tree whose nodes hold BB keys needs only about log⁡B+1N\log_{B+1} N misses, roughly log⁡2B\log_2 B times fewer, which is why databases and file systems use them. The next lesson proves that no comparison-based search can do better.

Key takeaways

  • A fetch costs about a nanosecond from L1, about 100 ns from DRAM and milliseconds from a hard disk; caches move whole lines (64 bytes on most x86 processors, 128 on Apple's M-series), so good algorithms use all of each line and reuse it while it is cached.
  • In the ideal-cache model a scan of NN words costs Θ(N/B)\Theta(N/B) misses, the best possible, while pointer chasing over scattered nodes costs Θ(N)\Theta(N), and its dependent misses cannot overlap. Optimal replacement is justified by LRU's 2-competitiveness with twice the capacity.
  • Loop order and layout decide the miss count: walk row-major arrays by rows, store fields read together in their own arrays, and keep data written by different threads in different lines.
  • Tiled matrix multiplication incurs Θ(n3/(BM))\Theta(n^3/(B\sqrt M)) misses, matching the Hong–Kung lower bound for the classical algorithm, which the Loomis–Whitney inequality proves in a few lines.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A linked list and an array hold the same NN values, and the list's nodes are scattered over a region much larger than the cache. Besides incurring more misses, why does the list traversal run far slower per miss than the array scan?

  1. Each node's address is known only after the previous node arrives, so its misses happen one at a time and cannot be prefetched, while the scan's misses are independent and overlap
  2. Pointers are 8 bytes, so a list node is always bigger than a cache line
  3. The processor must check each pointer for null, and that check takes about 100 ns
  4. Caches store only arrays, never linked-list nodes
Show the answer

A. Each node's address is known only after the previous node arrives, so its misses happen one at a time and cannot be prefetched, while the scan's misses are independent and overlap

A scan's addresses are known in advance: the prefetcher fetches lines ahead and the processor keeps many misses in flight, so the scan is limited by bandwidth. Pointer chasing serializes the misses and pays one full memory latency, about 100 ns, per node.

Question 2

Tiled matrix multiplication uses tiles of side t=Θ(M)t = \Theta(\sqrt M). If the cache becomes four times larger and the tiles are resized to match, how does the number of cache misses change, for large nn?

  1. It falls by a factor of 4
  2. It is unchanged
  3. It falls by a factor of 2
  4. It falls by a factor of 16
Show the answer

C. It falls by a factor of 2

The misses are Θ(n3/(BM))\Theta(n^3/(B\sqrt M)), so quadrupling MM doubles M\sqrt M and halves the misses: tiles twice as wide reuse each fetched number twice as often.

Question 3

Which statement about the Hong–Kung lower bound is correct?

  1. Every matrix multiplication algorithm must move Ω(n3/M)\Omega(n^3/\sqrt M) words
  2. Any schedule of the classical algorithm, which forms all n3n^3 products, must move Ω(n3/M)\Omega(n^3/\sqrt M) words, so tiling is optimal for it up to a constant factor
  3. It shows that the i,k,ji, k, j loop order is optimal
  4. It bounds the number of arithmetic operations, not data movement
Show the answer

B. Any schedule of the classical algorithm, which forms all n3n^3 products, must move Ω(n3/M)\Omega(n^3/\sqrt M) words, so tiling is optimal for it up to a constant factor

The bound counts transfers for algorithms that form all n3n^3 products AikBkjA_{ik}B_{kj}, and tiling matches it. Strassen-like algorithms form fewer products, and their communication is bounded by different arguments.

Question 4

The ideal-cache model assumes the cache evicts the line used furthest in the future, which no real cache can know. Why are bounds proved in the model still meaningful?

  1. Real caches do implement furthest-in-future replacement
  2. The replacement policy never changes the number of misses
  3. LRU with twice the capacity incurs at most twice the optimal policy's misses, so for algorithms whose misses change by a constant factor when MM doubles, the bounds carry over up to a constant
  4. LRU is itself optimal for every sequence of accesses
Show the answer

C. LRU with twice the capacity incurs at most twice the optimal policy's misses, so for algorithms whose misses change by a constant factor when MM doubles, the bounds carry over up to a constant

This is Sleator and Tarjan's competitive analysis of paging: with twice the capacity, LRU is 2-competitive against the optimal policy. Almost every algorithm analyzed in the model is regular in this sense.

Further reading

  • M. Frigo, C. E. Leiserson, H. Prokop & S. Ramachandran, "Cache-oblivious algorithms," Proceedings of FOCS (1999); journal version in ACM Transactions on Algorithms 8(1) (2012).
  • J.-W. Hong & H. T. Kung, "I/O complexity: The red-blue pebble game," Proceedings of STOC (1981).
  • D. D. Sleator & R. E. Tarjan, "Amortized efficiency of list update and paging rules," Communications of the ACM 28(2) (1985), 202–208.
  • U. Drepper, "What Every Programmer Should Know About Memory" (2007).
  • J. L. Hennessy & D. A. Patterson, Computer Architecture: A Quantitative Approach, 6th ed. (Morgan Kaufmann, 2017), chapter 2 (memory hierarchy design).