Sub topic 7
Cache locality: why arrays often win in practice
This chapter assumes you know Big-O basics, understand that a linked list node holds a reference to the next node, and have read the earlier chapters on memory layout and traversal cost. Big-O counts operations. It does not say how long each operation takes, and that depends heavily on the CPU cache.
The memory hierarchy in one paragraph
A CPU reads from main memory (RAM) far more slowly than it reads from its own small, fast caches. The gap is roughly a factor of 50 to 100 for a cache miss, though the exact figure varies by hardware. When the CPU needs a byte that is not in cache, it fetches a whole cache line, typically 64 bytes, and stores it. The next access is fast if it lands in a line that is already cached.
Two kinds of locality
- Spatial locality means that after touching an address, you are likely to touch nearby addresses.
- Temporal locality means that after touching an address, you are likely to touch it again soon.
Arrays are strong on spatial locality. Elements sit side by side, so one cache line load brings in several neighbours. Walking an array of 8-byte values loads one line per 8 elements, and the hardware prefetcher also notices the sequential pattern and loads ahead.
A linked list node is allocated separately. Consecutive nodes may be far apart in memory, so each node.next can trigger a fresh cache miss. The CPU also cannot start loading node 5 until node 4 has arrived, because node 4 holds the address of node 5. This is called pointer chasing, and it stops the CPU from overlapping memory requests.
Measuring it
The program below builds a million-element array and a million-node linked list, then times a full traversal of each.
import time
class Node:
__slots__ = ("value", "next")
def __init__(self, value, next=None):
self.value = value
self.next = next
def sum_array(items):
total = 0
for x in items:
total += x
return total
def sum_linked(head):
total = 0
node = head
while node is not None:
total += node.value
node = node.next
return total
N = 1_000_000
items = list(range(N))
head = None
for v in reversed(range(N)):
head = Node(v, head)
start = time.perf_counter()
a = sum_array(items)
t_array = time.perf_counter() - start
start = time.perf_counter()
b = sum_linked(head)
t_linked = time.perf_counter() - start
assert a == b
print(f"array: {t_array:.3f}s")
print(f"linked: {t_linked:.3f}s")Both traversals are O(n), so Big-O rates them as equal. On most machines the linked version still runs slower.
The Python gap is modest because of how the interpreter works. A Python list stores references to objects, not the values themselves, so the integers are already scattered on the heap. The interpreter's per-step overhead also hides much of the memory cost. In C, C++, Rust or Java with primitive arrays, the values really are contiguous, and the gap is often several times larger.
When locality changes the answer
Locality matters most when the work per element is small and the structure is large. Examples are summing, filtering, scanning for a value, or copying. Here the memory system sets the speed limit, not the arithmetic.
This changes some familiar comparisons. Inserting into the middle of an array costs O(n) element shifts, but those shifts are a sequential block move that the hardware does very quickly. Finding the insertion point in a linked list costs O(n) pointer chasing, with a likely cache miss at each step. For lists of moderate size, the array can win even on insert-heavy workloads when you must search for the position first.
Linked lists keep their advantage when you already hold the node and the structure is large, as in the unlink example from the earlier chapter. There, no search or shifting happens at all.
Common errors
- Quoting Big-O as if it were a timing. Two O(n) loops can differ by a large constant factor.
- Assuming the benchmark language matches production. Results from Python do not transfer directly to a language with unboxed arrays.
- Benchmarking tiny inputs. If everything fits in cache, the difference mostly disappears. Test at sizes close to your real workload.
- Ignoring allocation cost. Each linked list node is a separate allocation, which also adds time and is covered in the memory overhead chapter.
Exercise
A program stores 5 million small records and repeatedly scans all of them to compute a total. A teammate proposes a linked list because "we sometimes remove records." Both structures scan in O(n). Give two reasons the array is likely to scan faster, and one condition under which the linked list would still be the better choice.
Show answer
First, array elements are contiguous, so each cache line load serves several records and the prefetcher can read ahead. Second, linked list traversal is pointer chasing, so each node's address is unknown until the previous node loads, which causes cache misses and prevents overlapping memory requests. The linked list is still better if removals are frequent, the program already holds references to the nodes it removes, and the removals cost more overall than the scans. Then O(1) unlinking beats O(n) shifting.