How computers work

Cache: why the processor doesn’t wait for memory

Main memory responds in 70–100 nanoseconds — that is 300–500 processor clock cycles. A cache is a small, fast memory next to the core that keeps copies of recently needed data. Almost all accesses hit the cache, and the processor almost never waits. The educational model shows the simplest possible cache: 8 lines of 16 bytes, direct-mapped, write-through — and all the main principles are visible in it.

Open in 3D →

The memory wall: why a cache is needed

Since the 1980s, processor speed has grown much faster than memory speed. A 5 GHz core completes a cycle in 0.2 ns, while a DDR5 module returns the first data 70–100 ns after a request. If every load went to memory, the core would sit idle for hundreds of cycles on every fifth instruction — and loads and stores make up about a third of all instructions.

Making all memory fast is impossible: fast memory (SRAM) takes up dozens of times more silicon area than dense memory (DRAM), costs more and has to sit physically close to the core — a signal traveling a few centimeters along a wire to the memory module and back already needs nanoseconds, and there are controllers and a protocol along the way too.

The way out is a hierarchy: a very small and very fast memory right at the core, a larger and slower one a bit farther away, and a huge slow one on the motherboard. Each level holds copies of what is most likely to be needed soon. This works because programs do not access memory at random.

Locality: why the cache guesses right

Temporal locality: what was used recently is likely to be needed again. A loop variable, a counter, the top of the stack, the code of the loop itself — they are accessed thousands of times in a row. So it pays to keep what was read recently close at hand.

Spatial locality: if address X was read, X + 1, X + 2… are likely to be needed soon. Arrays are traversed sequentially, program instructions follow one another, the fields of a structure sit next to each other. So it pays to load not a single byte but a whole block of neighbors at once — a cache line.

On typical programs the L1 data cache serves 90–98% of accesses, and together with L2 and L3 only a few percent of requests make it all the way to memory. But there are also “bad” programs — walking a linked list scattered across memory, or random access to a huge table: there is no locality there, and the cache barely helps.

Where the address comes from

The core’s load-store unit issues the address the instruction needs: a register plus an offset, computed in the AGU. In the educational model the address is 16 bits; in a real processor the virtual address is 48–57 bits, and the physical one up to 52 bits.

The cache splits this address into three fields. Offset — the low bits, the number of the byte within a line. Index — the middle bits, the number of the line (in an associative cache, the number of the set). Tag — all the remaining upper bits: by them the cache knows whose copy is sitting in the line.

The demo walks through an array the way a typical program does: neighboring addresses in a row, then a return to something already read, then an address that gets in the way, and two writes.

Breaking down an address: tag, index, offset

In the model a line is 16 bytes, so the offset takes the 4 low bits (2⁴ = 16). There are 8 lines, so the index takes the next 3 bits (2³ = 8). The remaining 9 upper bits of the 16-bit address are the tag. In total the cache holds 8 × 16 = 128 bytes of data.

Example: address 0x0104 = 0000 0001 0000 0100 in binary. The low 4 bits 0100 are offset 4. The next 3 bits 000 are index 0. The upper 9 bits 000000010 are tag 2. So the byte is (if it is cached at all) in line 0, at position 4, and the line must have tag 2.

Address 0x0500 = 0000 0101 0000 0000: offset 0, index 0, tag 10. The same index as 0x0104 but a different tag — these addresses compete for the same cache line. Address 0x0110: offset 0, index 1, tag 2 — the neighboring line.

Splitting an address into fields costs nothing: they are simply different wires of the same address bus, with no computation at all. That is why line sizes and line counts are always powers of two.

Cache lines: valid, tag, data

A cache stores data in lines — blocks of 16 bytes in the model and 64 bytes in real x86 and ARM processors. Each line has a valid bit (whether it holds anything at all), a tag (whose copy it is) and the data itself. At power-on all valid bits = 0: the cache is empty.

The educational cache is direct-mapped: each address can live in only one line, the one whose number is its index. This is the simplest scheme: to find data, it is enough to select one line and check its tag.

A line is loaded in full. Having read byte 0x0100, the cache also brings in its 15 neighbors, 0x0100–0x010F: the next accesses 0x0104, 0x0108, 0x010C hit the cache for free. This is spatial locality in action. In a real processor a 64-byte line holds 8 numbers of 64 bits or 16 of 32 bits.

Tag comparison: hit or miss

The index selects a line, and its tag is compared with the address’s tag. If they match and valid = 1, it is a hit: the offset selects the needed bytes, and the data is ready in 1 ns in the model (about 4–5 cycles of L1 in a real core). If they don’t match, it is a miss: the line is loaded from memory (80 ns in the model) and written in place of the old one, after which the data is handed to the core.

Comparing tags is an XOR of each pair of bits followed by an OR tree: a result of 0 means “equal.” The comparison runs at the same time as the line’s data is read so as not to lose time: the data is read in advance, and the hit signal merely permits it to be used.

If two addresses have the same index but different tags, they evict each other even in an almost empty cache — this is a conflict miss. In the demo, 0x0500 knocks out the 0x0100 line, and the next read of 0x0100 knocks out 0x0500, even though the other 6 lines are free.

Misses are usually divided into three kinds. Compulsory misses — the first access to a line; they cannot be avoided. Capacity misses — there is more data than fits in the cache. Conflict misses — caused by addresses sharing the same slot. Associativity is the remedy for the last kind.

The demo step by step: ten accesses

1) Read 0x0100: line 0 is empty — a miss; the line 0x0100–0x010F with tag 2 is loaded, 81 ns. 2–4) Reads of 0x0104, 0x0108, 0x010C: same index and tag — three hits at 1 ns each. 5) Read 0x0110: index 1, the line is empty — a miss, the next line is loaded. 6) 0x0104 again: line 0 is still in place — a hit (temporal locality).

7) Read 0x0500: index 0, tag 10 does not match 2 — a conflict: the 0x0100 line is evicted and 0x0500 is loaded. 8) 0x0100 again: another conflict, the lines swap places. Two misses in a row with an almost empty cache — the price of direct mapping.

9) Write 0x0114: line 1 is in place — a write hit; the data is updated in the line and at the same time sent to memory (write-through), 80 ns. 10) Write 0x07F0: index 7, the line is absent — a write miss; in this model the line is not loaded, the data is simply written to memory.

Result: 5 hits out of 10, about 490 ns in total. Without a cache the same 10 accesses would have taken 800 ns; with a real write-back policy and associativity, noticeably less. Watch the average access time as the demo runs: it drops with every hit.

Associativity and replacement

In a set-associative cache the index selects not one line but a set of N lines — ways. Data can live in any line of its set, so the tag is compared with all N tags of the set at once, in parallel. In the educational model N = 1; the L1 caches of modern cores are 8–12-way, L2 is 8–16-way, L3 is 12–20-way.

With associativity, 0x0100 and 0x0500 would sit peacefully in two ways of the same set. The price is N comparators instead of one plus a multiplexer selecting the data of the right way — that is, more energy and slightly more delay.

When a set is full, you have to decide whom to evict. The ideal choice is the line that won’t be needed for the longest time, but the future is unknown. In practice the line that has gone unused the longest is evicted (LRU), or a cheap approximation of it (pseudo-LRU on a tree of bits). Last-level caches use cleverer policies that recognize a one-time pass over a large array so that it doesn’t wash out useful data.

Memory, the data bus and the write policy

On a miss, a line travels from main memory over the data bus to the memory controller in the processor and on into the cache. A 64-byte line is sent over a DDR5 bus as a burst of 16 transfers of 32 bits on one subchannel — this is the standard unit of exchange between the processor and memory. Double-clicking the memory opens its inner workings.

Writes in the educational cache are write-through: data is written to both the cache and memory at once. On a write miss the line is not loaded into the cache (no-write-allocate). This is simple and reliable — memory is always up to date — but every write occupies the bus and waits for memory.

Real caches use write-back with the line loaded on a write miss (write-allocate). A write changes only the line in the cache and marks it “dirty.” The line goes to memory once — when it is evicted. If a loop increments one variable a thousand times, a single write goes to memory instead of a thousand. And the core doesn’t even wait for the cache: writes accumulate in the store buffer.

Write-back creates a problem: memory may hold a stale value while the fresh one sits in the cache of one of the cores. How cores come to an agreement about this is covered on the “Die” level (cache coherence).

The cache hierarchy in a processor

A modern core: L1 instruction cache of 32–64 KB and L1 data cache of 32–48 KB (4–5 cycles, about 1 ns), a private L2 of 1–3 MB (14–17 cycles, about 3 ns), an L3 of 16–36 MB shared by all cores (40–50 cycles, about 10 ns), and main memory at 300–500 cycles, 70–100 ns. Each level is roughly an order of magnitude larger and 3–4 times slower than the previous one.

The average access time is computed with the formula: hit time + miss rate × miss penalty. With 1 ns per hit, 5% misses and an 80 ns penalty, we get 1 + 0.05 × 80 = 5 ns — already five times worse than a pure hit. That is why even a few percent of misses matter so much, and why the intermediate levels L2 and L3 are needed: they turn many 80-nanosecond misses into 3- and 10-nanosecond ones.

Caches also prefetch: a prefetch unit notices that the program is walking through addresses with a constant stride and loads the next lines in advance. When an array is traversed sequentially, almost all misses disappear.

Caches take up more than half of the die area — look on the “Die” level at how much space is given to L2 and L3.

What a cache is made of

A cache is arrays of static memory, SRAM: each bit is stored in a loop of two inverters with two access switches, 6 transistors per bit. A cell in a 3 nm process takes about 0.02 µm². SRAM doesn’t need refreshing like DRAM and is read in a fraction of a nanosecond, but it is several dozen times larger than a DRAM cell.

Reading works like this: the index decoder activates one row — a “word line”; the cells of that row begin to slightly discharge pairs of “bit lines,” and sense amplifiers detect a difference of a few dozen millivolts long before the full swing. This is exactly why a large array is slower than a small one: longer lines, more capacitance, longer discharge.

Besides data, a cache stores tags, valid and dirty bits, bits for the replacement policy and error-correcting codes (ECC): in L2 and L3 caches a single random bit error is corrected on the fly. Shrinking SRAM is getting harder and harder: in 3 and 2 nm processes the cell has barely shrunk, so manufacturers move cache onto separate dies (AMD 3D V-Cache places an extra 64 MB L3 cache die directly against the die with the cores — on top of it, and in Zen 5, underneath it).

Virtual addresses and the TLB

Programs work with virtual addresses: each process has its own address space, and the operating system uses page tables to map its pages (usually 4 KB each) onto physical memory. Translating an address through a multi-level table in memory takes 4–5 accesses — too expensive for every load.

That is why a core has a TLB — a small cache of translations: 64–128 entries at the first level and 2–4 thousand at the second. A TLB lookup happens in parallel with the L1 access.

This has an unexpected consequence for L1 sizes. To read L1 without waiting for address translation, the index is taken from the low 12 bits of the address, which within a 4 KB page are the same in the virtual and physical addresses. Then a single way of the cache cannot be larger than 4 KB, and L1 capacity = 4 KB × the number of ways: 8 ways gives 32 KB, 12 ways gives 48 KB. These are exactly the L1d sizes found in real cores.

What this means for a programmer

Traversing a two-dimensional array row by row (in the order it is laid out in memory) moves sequentially through cache lines. Traversing the same array column by column jumps across thousands of bytes, and every access can be a miss: the difference in speed can be 5–10 times with the same number of operations.

An array of structures where only one field is needed from each structure drags all the other fields into the cache too. Sometimes it is better to store data “by columns” — a separate array for each field. Linked lists and trees with nodes scattered across memory are slower than arrays for the same reason.

Two threads on different cores that write to different variables sitting in the same 64-byte line get in each other’s way: the line bounces between the cores on every write (false sharing). The cure is to align the data to line boundaries.

Common misconceptions

“The cache is part of main memory.” No: the cache is a separate memory inside the processor, on the same die as the cores. A program does not control it directly — it is transparent, and the program runs as if it weren’t there, only faster.

“A bigger cache is always faster.” A large array is slower than a small one, which is why L1 has stayed at 32–64 KB for twenty years now. Capacity grows at the farther levels, where the latency is higher anyway.

“The cache stores individual variables.” It stores 64-byte lines — copies of chunks of memory, regardless of what they contain.

Open in 3D →

All articles

Overviews

Logic: from transistor to arithmetic

Processor

Computer

Servers and data centers

Networks and the internet

Software