Search

Search papers and lessons

Memory Hierarchy

Level 1 · 9 min read

Computers keep data in several levels of storage, from tiny and fast registers to huge and slow disks, and programs run fast when they reuse data that sits near the top.

On this page

TL;DR

A computer does not keep all its data in one kind of memory. It uses a ladder of storage: a few bytes in registers next to the arithmetic, megabytes of cache, gigabytes of main memory, and then disks that hold terabytes but respond thousands of times more slowly. Faster levels are smaller, so the question for a program is how often it asks for data that is not already on a high rung.

Where you'll see it: in why looping over an array in the right order can be several times faster, in why a database keeps hot rows in memory, and in why GPU programmers tile their work (see GPU memory).

Intuition

A desk, a shelf, and a basement

Picture a researcher. The book she is reading sits open on her desk. Books she used this week are on a shelf beside her. Older books are in the library basement, and anything else is in a warehouse across town.

The desk is small but she reaches it in a second. The basement is large, and every trip down takes minutes. The warehouse takes a day. She works fastest when the books she needs are already on the desk. She does not need to be faster at reading. She needs to walk less.

A computer has the same shape. The processor is the researcher. Registers are the desk: a handful of values the arithmetic can use directly. Caches are the shelf. Main memory is the basement. Disks are the warehouse.

flowchart TB
  A["Registers: a few values, under one nanosecond"] --> B["Cache: kilobytes to megabytes, a few nanoseconds"]
  B --> C["Main memory: gigabytes, around a hundred nanoseconds"]
  C --> D["Solid-state disk: terabytes, tens to hundreds of microseconds"]
  D --> E["Hard disk: terabytes, milliseconds"]

Each level is larger than the one above it and slower to reach. The times and sizes in the diagram are rough orders of magnitude. They change from one machine to another, but the shape of the ladder is the same across machines.

Why the ladder exists

Fast memory costs more per byte and takes more space near the processor. Large memory costs less per byte and can sit further away. If a computer had only one kind of memory, it would have to choose between small and fast, or large and slow. Stacking levels lets it have most of the speed of the small one and most of the capacity of the large one, provided programs use the small levels well.

That condition is the whole idea. A hierarchy only helps when the data a program needs is already on a high level. The rest of this lesson is about when that happens.

The math

Why programs reuse data

Two patterns make a hierarchy work. Each is a name for a common property of programs.

Temporal locality. A value used once is likely to be used again soon. A loop counter, or a constant used in every step of a calculation, is read many times in a short period.

Spatial locality. A value at one address makes its neighbours likely to be used soon. Reading element 5 of an array makes elements 6, 7 and 8 likely next.

Hardware exploits spatial locality by moving data in blocks. A cache does not fetch one byte when it misses. It fetches a cache line, a fixed-size block that is commonly 64 bytes on current desktop and server processors. The next few reads from the same line are then fast.

Average access time

If a fraction hh of accesses are served by the fast level, that level takes time tfastt_{fast}, and a miss costs an extra tslowt_{slow}, then the average time per access is

tavg=tfast+(1−h) tslowt_{avg} = t_{fast} + (1 - h)\, t_{slow}

Every access pays the fast cost. Only the misses pay the extra penalty. The formula is the simplest form of what architecture courses call average memory access time. Real systems have several levels, and the same idea applies level by level.

0.90.920.940.960.981024681012hit rate haverage access time (ns)
  • t_avg with t_fast = 1 ns, t_slow = 100 ns
Each extra percent of hit rate removes a percent of the 100 ns penalty. The two points are the worked example below.

Worked examples

Example
Two hit rates, same hardware

Take a fast level that answers in 1 ns and a slow level that adds 100 ns on a miss.

  1. With a hit rate of 95%, the miss rate is 1−0.95=0.051 - 0.95 = 0.05.
  2. The average is tavg=1+0.05×100=1+5=6t_{avg} = 1 + 0.05 \times 100 = 1 + 5 = 6 ns.
  3. With a hit rate of 99%, the miss rate is 0.010.01.
  4. The average is tavg=1+0.01×100=1+1=2t_{avg} = 1 + 0.01 \times 100 = 1 + 1 = 2 ns.
  5. Raising the hit rate from 95% to 99% cuts the average time by a factor of 3, and the hardware did not change.

Interpretation: the fast level's speed matters less than its hit rate once misses are costly. A program that finds its data in the cache four more times in a hundred can be three times faster.

Example
Walking an array in two orders

A program sums a 1000 by 1000 table of 8-byte numbers stored row by row, so each row is one contiguous block of 8000 bytes. Assume a cache line is 64 bytes and the cache is too small to hold the whole table.

  1. Row by row: consecutive elements share a cache line. One line holds 64/8=864 / 8 = 8 numbers. So the table needs 1,000,000/8=125,0001{,}000{,}000 / 8 = 125{,}000 line fetches.
  2. Column by column: the next element in a column is 8000 bytes away, in a different row. Each access lands on a line that is not in the cache. If the cache cannot keep the lines from the previous column, that is one fetch per element, so 1,000,0001{,}000{,}000 fetches.
  3. The two orders do the same additions. The column order does eight times as many line fetches.

Interpretation: the arithmetic is identical, but the memory traffic differs by a factor of eight in this case. Real programs also depend on the prefetcher and on how big the cache is, so the measured gap can be smaller or larger. The counting here is the reason to expect a gap, not a measurement of one.

Tradeoffs and failure modes

A hierarchy is a bet that the working set is small enough to fit in the fast levels. When the bet fails, programs slow down in ways that can be hard to see in the code.

SituationWhat goes wrongBetter choice
Large data traversed in a poor orderEach access misses the cacheWalk memory in the order it is stored
Working set larger than the cacheLines are evicted before they are reusedProcess data in blocks that fit, which is tiling
Random access to a large file on diskEach read pays the disk delayBatch reads, or keep the index in memory
Many small objects scattered in memoryLittle spatial locality, so each access loads a new lineStore related values together in arrays

Many fast levels also mean many places where a value can be stale. Hardware keeps copies consistent, but that work costs time, and programs that share data across cores pay for it.

History

Virtual memory and early paged systems appeared in the early 1960s, when machines needed to run programs bigger than their main memory. A paper by Maurice Wilkes in 1965 described the idea of a small fast "slave" memory that holds copies of the contents of a larger, slower memory. Later machines of the late 1960s put cache memory into production. Cache hierarchies with several levels spread through processor designs over the following decades, as the gap between processor speed and memory speed grew. The ladder shown here is the result of that growing gap, not a fixed design.

Check yourself

QuestionWhich kind of locality explains why reading the next element of an array is fast after reading the current one?Show answer

Spatial locality. Values at neighbouring addresses are likely to be used soon, and the cache fetches a whole line, so the next few elements are already on the fast level. Temporal locality is the related idea that a value used once is likely to be used again soon, such as a loop counter.

QuestionA fast level answers in 2 ns, a miss adds 150 ns, and the hit rate is 90%. What is the average access time?Show answer

The miss rate is 0.10. The average is 2+0.10×150=2+15=172 + 0.10 \times 150 = 2 + 15 = 17 ns. If the hit rate rises to 98%, the miss rate is 0.02 and the average is 2+0.02×150=52 + 0.02 \times 150 = 5 ns. The hit rate matters more than the fast level's speed here, because the miss term dominates the sum.

QuestionWhy does a program that visits a large array in column order often run more slowly than one that visits it in row order, even though both do the same additions?Show answer

Elements are stored row by row, so consecutive elements in a row share a cache line. Walking down a column jumps by a full row each time, so each access lands on a line the cache does not hold. The program then pays a slow fetch per element instead of one fetch per eight elements. The arithmetic is unchanged, so the difference is entirely in memory traffic.

QuestionYou need to sum the values of a list of 10 million numbers that fits in RAM but not in cache. Would you rather store it as one array, or as 10 million small objects linked by pointers? Why?Show answer

Store it as one array. The array's values sit next to each other in memory, so spatial locality works and each cache line brings in several values. Linked small objects are scattered through memory, so most accesses miss the cache and each one pays the main-memory delay. The sum takes the same number of additions either way.

Sources