Sub topic 13
Cache Locality and Real-World Speed
This chapter assumes you know Big-O notation, that an array occupies one contiguous block of memory, and that indexing is O(1). Big-O counts operations. It ignores how long each operation takes. This chapter covers why arrays are often faster than their operation counts suggest.
Memory is a hierarchy
A CPU reads from several kinds of memory. Each level is larger and slower than the one before it.
| Level | Typical size | Typical access time |
|---|---|---|
| Registers | A few hundred bytes | Under 1 ns |
| L1 cache | 32 to 64 KB | About 1 ns |
| L2/L3 cache | Hundreds of KB to tens of MB | 3 to 15 ns |
| Main memory (RAM) | Gigabytes | 60 to 100 ns |
These numbers vary by machine, but the gap between cache and RAM is usually 10 to 100 times.
The CPU does not fetch one byte at a time from RAM. It fetches a cache line, a block of usually 64 bytes, and keeps it in cache. If your next read falls inside a line already loaded, it is a cache hit and is fast. If not, it is a cache miss and the CPU waits for RAM.
Why arrays suit the cache
Because array elements are adjacent, one cache line holds several of them. An array of 8-byte integers fits 8 elements per line. Reading element 0 loads elements 0 to 7, so the next 7 reads hit the cache. This is spatial locality: nearby addresses are used close together in time.
CPUs also notice sequential access and prefetch, loading the next lines before you ask for them. A plain loop over an array is the pattern they handle best.
Comparing access patterns
Both loops below do the same amount of work, n additions over the same data. They differ in the order of access.
import random
import time
n = 5_000_000
data = list(range(n))
order = list(range(n))
random.shuffle(order)
start = time.perf_counter()
total = 0
for i in range(n):
total += data[i]
sequential = time.perf_counter() - start
start = time.perf_counter()
total = 0
for i in order:
total += data[i]
shuffled = time.perf_counter() - start
print(f"sequential: {sequential:.2f}s")
print(f"shuffled: {shuffled:.2f}s")The shuffled loop is usually slower, even though Big-O says both are O(n). Exact timings depend on your machine. In Python the gap is smaller than in C or Java, because each list slot holds a pointer to an object and interpreter overhead hides part of the difference.
Where this matters
- Arrays versus linked lists. Linked list nodes are allocated separately and can be scattered across RAM. Traversal can cause a cache miss per node. A dynamic array often beats a linked list even for operations where the linked list wins on paper, such as inserting in the middle of a small or medium collection.
- Arrays of pointers. A Python list or a Java
ArrayList<Integer>stores references. The references are contiguous, but the objects they point to may not be. Arrays of primitive values, such as Javaint[], C++std::vector<int>, or NumPy arrays, keep the data itself contiguous. - Resizing. Copying into a new block is a sequential copy, which is the cache-friendly case. It is one reason the occasional O(n) resize costs less in practice than you might fear.
Common mistakes
- Concluding that a data structure is faster from its Big-O alone.
- Benchmarking with tiny data that fits entirely in cache.
- Assuming a list of objects has contiguous data. Only the references are contiguous.
Exercise
A program sums one million integers stored in a C++ std::vector<int>. A second program sums one million integers stored in a linked list. Both are O(n). Which is likely faster, and why?
Show answer
The vector is likely faster. Its elements are contiguous, so each 64-byte cache line holds 16 four-byte ints and the prefetcher can load ahead. Linked list nodes may be scattered in memory, so traversal can incur a cache miss for many nodes, and each node also stores an extra pointer, which means fewer useful values per cache line.