When Theory Meets Reality
Big-O describes how cost grows and drops constant factors. On real hardware a constant can be 50, and n is a number you can look up. The fastest approach comes from combining the growth rate with 3 practical costs: the interpreter, memory layout, and storage access.
The interpreter's constant factor
Python executes a loop body 1 bytecode instruction at a time. Built-ins such as sum, sorted, str.join and set operations run their loops in C. Two functions with the same O(n) growth can differ several times in speed:
import timeit
values = list(range(1_000_000))
def loop_sum():
total = 0
for v in values:
total += v
return total
print("loop:", timeit.timeit(loop_sum, number=10))
print("sum: ", timeit.timeit(lambda: sum(values), number=10))Run it on your machine: the built-in typically finishes several times sooner. The seconds vary between machines; the ratio is what carries over. The same effect lets an O(n log n) sorted call in C beat an O(n) pure-Python loop at the sizes your pipeline sees, so measure before swapping one for the other.
Memory layout and the cache
A CPU fetches memory in cache lines, commonly 64 bytes on x86 processors, so reading neighbouring values is cheap and jumping around is expensive. One line of contiguous 8-byte numbers delivers 8 usable values. One line of a Python list delivers 8 pointers, and each int they point to is a separate object elsewhere in memory, often a fetch of its own. Contiguous storage pays off when C code walks the buffer: a columnar file reader decoding a whole column, or a numeric routine that takes the buffer directly. Iterating an array.array from Python gains nothing, because every element read builds a new int object, so a Python loop or sum over it runs no faster than over a list and often slower. Columnar file formats keep each column contiguous for the same reason: a query that reads 3 of 40 columns fetches only those 3, in order.
Storage: when a full scan beats an index
An index finds 1 row in O(log n), which sounds unbeatable next to an O(n) scan. A query matching many rows changes that: each match costs a random read of its page, while the scan reads every page in order. The model below charges a random page read 50 times a sequential one; replace 50 with your own hardware's ratio.
rows, rows_per_page = 1_000_000, 100
SEQUENTIAL, RANDOM = 1, 50
def scan_cost():
return rows // rows_per_page * SEQUENTIAL
def index_cost(matches):
return matches * RANDOM
for matches in [10, 100, 200, 1_000, 50_000]:
plan = "index" if index_cost(matches) < scan_cost() else "scan"
print(matches, index_cost(matches), scan_cost(), plan)Output:
10 500 10000 index 100 5000 10000 index 200 10000 10000 scan 1000 50000 10000 scan 50000 2500000 10000 scan
With 10,000 pages to scan, the index wins only while matches × 50 stays under 10,000, so it loses from 200 matching rows on: 0.02% of the table. Query planners make this same call from row-count estimates, which is why a stale estimate can turn a fast query slow.
Choosing in practice
- Do
- Time both candidates with timeit at your real n before rewriting
- Push hot loops into built-ins: sum, sorted, set operations, str.join
- Read only the columns you need, in sequential order
- Recompute crossovers when hardware or data volume changes
- Avoid
- Pick an algorithm from Big-O alone when n is a few hundred
- Use an index for a query that matches a large share of rows
- Hand-write a Python loop to beat a C built-in of the same order
- Trust a single timing run; repeat it and compare the fastest
In this section's model, faster storage drops the random read cost from 50 units to 5, and the scan still costs 10,000. A query matches 1,500 rows. Which plan wins?
- Scan, because 1,500 matches is well past the 200-row crossover
- Index, because 1,500 × 5 = 7,500 units is below the scan's 10,000
- Scan, because faster storage cuts the scan's cost by the same factor
- Index, because an O(log n) lookup always beats an O(n) scan
About this lesson
This section is part of the Complexity: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.