Spatial and temporal locality are two key principles that explain why programs tend to access certain blocks of memory in predictable patterns—insights that hardware (like CPU caches) exploits to boost performance.
1. Temporal Locality
• Definition: If a program accesses a particular memory location at time T, it is likely to access the same location again at some later time T′ (where T′ > T).
• Example:
- Looping over an array element multiple times.
- Repeatedly reading from or writing to the same variable in quick succession.
• Hardware Benefit:
- Caches keep recently used data “hot.” A cache line containing that data stays valid so that subsequent accesses hit in the fast cache rather than going out to slower main memory.
2. Spatial Locality
• Definition: If a program accesses a memory location at address A, it is likely to also access nearby addresses A + δ (where δ is small) soon after.
• Example:
- Iterating through the elements of an array in order (A[0], A[1], A[2], …).
- Traversing a struct’s fields in sequence.
• Hardware Benefit:
- Caches fetch whole cache lines (e.g., 64 contiguous bytes) at once. If you access A, the fetched line also contains addresses A + 1, A + 2, etc., so those accesses hit in-cache.
Quick Comparison Table
| Aspect | Temporal Locality | Spatial Locality |
|---|
| What’s reused? | Same memory location | Nearby memory locations |
| Typical pattern | Repeated use over time | Sequential or “clustered” access |
| Example | for (i…){ sum += x; } (same x) | for (i=0…N){ array[i] += 1; } |
| Cache behavior | Retain that cache line longer | Prefetch adjacent cache lines |
Why It Matters
Modern CPUs rely heavily on multi-level caches (L1, L2, L3). Exploiting both localities dramatically reduces average memory access time:
- Temporal → fewer misses on repeat accesses
- Spatial → fewer misses on nearby accesses
By writing code that reuses data soon after first use and processes data in contiguous blocks, you help the cache subsystem work more efficiently—yielding faster programs! 🚀