Sub topic 12
Memory layout and constant factors
This chapter assumes you know Big-O notation, Python lists, dictionaries and sets, and the structures from the earlier chapters. Big-O describes how cost grows with input size. It ignores the fixed cost of each step, and it ignores where the data sits in memory. Both can decide which structure is faster on real inputs.
Why layout matters
A processor reads memory through small, fast caches. When it loads one value, it also loads the neighboring bytes, called a cache line. Reading values that sit next to each other is cheap, because most of them are already in the cache. Reading values scattered across memory forces slow trips to main memory.
A contiguous array stores its elements side by side, so a scan mostly hits the cache. A linked list allocates each node separately, so every step may follow a pointer to a distant address. Both structures take O(n) to traverse, but the array is often several times faster in practice.
Python adds a layer
In CPython, a list stores an array of pointers to objects, not the values themselves. The pointers are contiguous, but the integers or strings they point to may not be. Locality is therefore weaker than in C. The array module and NumPy arrays store raw numbers contiguously and use much less memory.
import sys
from array import array
n = 100_000
as_list = list(range(n))
as_array = array("q", range(n)) # 8-byte signed integers
list_bytes = sys.getsizeof(as_list) + sum(sys.getsizeof(x) for x in as_list)
array_bytes = sys.getsizeof(as_array)
print(f"list: about {list_bytes} bytes")
print(f"array: about {array_bytes} bytes")The list figure counts the pointer array plus each integer object. The array figure is much smaller because the values are packed.
Constant factors
Big-O hides a multiplier. A hash lookup computes a hash, probes a table, and compares keys. A scan of a very short list skips all of that. For small inputs, the "slower" structure can win.
import timeit
def compare(n):
items = list(range(n))
as_set = set(items)
target = n - 1 # worst case for the list scan
t_list = timeit.timeit(lambda: target in items, number=100_000)
t_set = timeit.timeit(lambda: target in as_set, number=100_000)
return t_list, t_set
for n in (4, 1000):
t_list, t_set = compare(n)
print(f"n={n}: list {t_list:.4f}s, set {t_set:.4f}s")At n=4, the two times are close, and the list may even win. At n=1000, the set is far faster. Exact numbers depend on your machine.
How to apply this
- Choose by operations and Big-O first. This removes the clearly wrong options.
- If the remaining options are close, or
nis small, measure with realistic data. - Prefer contiguous structures (lists, arrays,
dequeblocks) when you mostly scan or append. - Consider packed arrays when you store millions of numbers and memory or scan speed matters.
- Do not give up a better complexity class for a speed-up you have not measured.
| Situation | Likely better choice | Reason |
|---|---|---|
| Under about 10 items, checked occasionally | List or tuple | No hashing overhead |
| Many membership checks on a large collection | Set | O(1) average beats scanning |
| Millions of numbers, scanned in order | `array` or NumPy | Packed values, good locality |
| Frequent pointer-chasing over scattered nodes | Rethink the layout | Cache misses dominate |
Exercise
A function checks whether a user role is one of three fixed strings, and it runs once per request. A teammate suggests replacing the tuple of three roles with a set because "sets are O(1)". Is that change worth making, and why?
Show answer
Probably not. With three items, a tuple scan costs about as much as hashing and probing a set, so the Big-O difference does not show up. The change would add little speed and make the code no clearer. Measure with timeit if you want proof. A set pays off as the collection grows or the check runs very often.