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.
Theory in plain words
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
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).
| Level | Size | Speed | Where |
|---|---|---|---|
| L1 cache | 8 to 64 KB | 1 to 4 cycles | inside each core |
| L2 cache | 256 KB to 4 MB | 10 to 20 cycles | per core or shared |
| L3 cache | 4 to 64 MB | 30 to 50 cycles | shared on PC and phone chips |
| Main RAM | GBs | 100+ cycles | off chip |
- Spatial locality: after using address X you will soon use X+1. Loop over arrays in memory order.
- Temporal locality: data used now will be used again soon. Keep hot data small.
- Cortex-M0/M3/M4 have no data cache; Cortex-M7 has. If DMA writes memory that the cache holds, invalidate the cache before reading.
- Peripheral registers must be mapped non-cacheable.
Quick quiz
1. What is a cache hit?
A hit is served without going to main memory.
2. Why are loops over arrays fast with a cache?
Nearby elements share the same cache line.
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.