36/39
Part 7 of 7 · Follow-upsLearn

Why do real systems so often prefer an array?

Locality. A CPU reads memory in blocks and keeps recent blocks in its cache, so reading items that sit side by side is cheap. Nodes sit wherever they were allocated, and each next can be a jump to memory that isn't cached.

Here are a million nodes made in order, then linked in a shuffled order:

# the Node above with __slots__
nodes = [SlotNode(v) for v in range(1_000_000)]
order = list(range(1_000_000))
random.Random(0).shuffle(order)
for i in range(len(order) - 1):
    nodes[order[i]].next = nodes[order[i + 1]]
Predict

A million nodes, linked once in the order they were made and once in a shuffled order. How much slower is the shuffled walk?

Pick an answer above to see the rest