Home / Learn Chip Programming / Cache Memory and Locality

Cache Memory and Locality

Cache is a small fast memory that holds recently used data. It makes slow main memory feel fast.

In shortCache is a small fast memory that holds recently used data. It makes slow main memory feel fast.

Theory in plain words

Cache address splitAddress = TAG | INDEX | OFFSETOFFSET: byte inside the lineINDEX: which cache lineTAG: which memory block is in that line
Cache address split

What it is

A cache stores copies of recently used memory blocks. A hit is served in a few cycles; a miss goes to slow memory. Programs reuse nearby addresses (locality), so most accesses hit.

Why we use it

Cache explains why loops over arrays are fast and random access is slow, and why DMA and cache can cause stale data bugs on Cortex-M7 and Linux systems.

How it works

The address is split into tag, index and offset. The index chooses a cache line, the tag says which block is stored there. If tags match it is a hit; otherwise the block is fetched.

Where it is used

  • Cortex-M7 and Cortex-A cores, PCs and phones
  • Performance tuning
  • DMA coherency bugs

Direct mapped cache simulator

Hits and missesTry it Yourself

Try 0 4 8 12 0 4 8 12: after the first pass everything hits. Try 0 16 0 16 0 16: addresses 0 and 16 map to the same line and keep evicting each other (a conflict miss).

LevelSizeSpeedWhere
L1 cache8 to 64 KB1 to 4 cyclesinside each core
L2 cache256 KB to 4 MB10 to 20 cyclesper core or shared
L3 cache4 to 64 MB30 to 50 cyclesshared on PC and phone chips
Main RAMGBs100+ cyclesoff chip
Careful:Never put peripheral register addresses in a cacheable region. The CPU would read a cached stale value instead of the live hardware.

Quick quiz

1. What is a cache hit?

2. Why are loops over arrays fast with a cache?

Common questions

What is a cache hit?

The data is found in the cache. A hit is served without going to main memory.

Why are loops over arrays fast with a cache?

Spatial locality. Nearby elements share the same cache line.