Sub topic 14
When Big O Is Not Enough: Constants, Caches, and Small Inputs
This chapter assumes you can read Big O expressions, know the common complexity classes, and have analyzed loops and recursion. You should also be comfortable running short Python scripts. Big O is the right tool for predicting how cost scales. It is a poor tool for predicting which of two algorithms is faster on a specific input size and machine. This chapter covers where the model stops working and what to do about it.
What Big O leaves out
Big O describes behavior as n grows without bound. It discards three kinds of information on purpose:
- Constant factors.
100nandnare both O(n). - Lower-order terms.
n^2 + 10^6 nis O(n^2), even though the second term dominates for any n below one million. - The cost model itself. Big O counts abstract steps, and it treats every step as equal.
All three are sensible simplifications for comparing growth. They become misleading when you use the result to pick an implementation for a fixed, finite workload. The formal definition states that some constant c and some threshold n0 exist. It does not say how large either one is.
Constants and the crossover point
Suppose algorithm A costs 100n steps and algorithm B costs n^2 steps. A is O(n) and B is O(n^2), so A wins asymptotically. B is cheaper for every n below 100, though, and the two tie at n = 100.
The crossover point is n = 100, and it depends entirely on the constant. If your inputs never exceed 50 items, the "worse" algorithm is the better choice. Before you pick on Big O alone, ask how large n really is in your workload.
Library authors use this effect routinely. Python's built-in sort (Timsort) uses insertion sort, which is O(n^2), to sort short runs. It then merges those runs. C++ std::sort implementations commonly switch to insertion sort for small partitions. A hybrid beats a pure O(n log n) algorithm because the simple algorithm has a very small constant.
Measuring the crossover yourself
The script below times insertion sort against merge sort on random lists of growing size. It uses only the standard library.
import random
import timeit
def insertion_sort(items):
a = list(items)
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
def merge_sort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
random.seed(1)
print(f"{'n':>6} {'insertion (s)':>14} {'merge (s)':>12}")
for n in (4, 8, 16, 32, 64, 256, 1024):
data = [random.random() for _ in range(n)]
reps = max(1, 20000 // n)
t_ins = timeit.timeit(lambda: insertion_sort(data), number=reps) / reps
t_mrg = timeit.timeit(lambda: merge_sort(data), number=reps) / reps
print(f"{n:>6} {t_ins:>14.2e} {t_mrg:>12.2e}")Exact numbers vary by machine and Python version, so no output is shown. On most machines insertion sort wins at the smallest sizes. Merge sort pulls ahead somewhere in the tens or low hundreds, and the gap then widens quickly. The point of the experiment is the shape of the result. The exact crossover size will differ on your machine.
Different operations cost different amounts
Big O usually counts "basic operations" as if each took the same time. Real operations differ by large factors:
| Operation | Rough cost |
|---|---|
| Arithmetic on registers | Under 1 ns |
| Read from L1 cache | About 1 ns |
| Read from main memory | About 50 to 100 ns |
| Read from SSD | Tens of microseconds |
| Network round trip within a data center | Hundreds of microseconds |
These are order-of-magnitude figures, and they change with hardware. An O(n) algorithm that makes n network calls can be far slower than an O(n log n) algorithm that works entirely in memory. Two algorithms with the same Big O can also differ by 100 times if one touches the disk or network and the other does not. When one step is a database query and another is an addition, counting them equally gives a wrong answer.
Caches and memory layout
Modern CPUs fetch memory in cache lines, typically 64 bytes at a time. Reading consecutive addresses is fast because the next values arrive with the first. Jumping around memory is slow because each access can miss the cache and wait on main memory. This is called locality of reference.
Two traversals of a 2D grid have the same Big O and different real cost:
import timeit
N = 2000
grid = [[1] * N for _ in range(N)]
def sum_by_rows(g):
total = 0
for r in range(N):
row = g[r]
for c in range(N):
total += row[c]
return total
def sum_by_columns(g):
total = 0
for c in range(N):
for r in range(N):
total += g[r][c]
return total
print("rows :", timeit.timeit(lambda: sum_by_rows(grid), number=3))
print("columns:", timeit.timeit(lambda: sum_by_columns(grid), number=3))Both functions perform N × N additions, so both are O(N^2). The column version also does an extra index lookup per step, which accounts for part of any gap you see. The rest comes from memory access order. In CPython the cache effect is muted, because a list stores pointers to objects rather than raw values. In C, C++, Rust, or NumPy, traversal order can change the runtime by several times for arrays that do not fit in cache.
The same idea explains a common surprise. Arrays beat linked lists for many workloads where Big O suggests otherwise. Inserting in the middle of an array is O(n) and in a linked list is O(1) once you hold the node. But the linked list scatters its nodes across memory, and finding the node costs a pointer chase at each step. For lists up to many thousands of elements, the array often wins.
Hidden costs inside "O(1)"
Treating an operation as O(1) hides several things:
- Hash tables. A lookup is O(1) on average, but it must compute a hash, and hashing a string of length k takes O(k). Collisions and resizing add variance. For a handful of items, a linear scan of a short list can match or beat a hash lookup.
- Amortized costs. A dynamic array append is O(1) amortized, yet a single append that triggers a resize copies every element. In a latency-sensitive system, such as a real-time loop or a request handler with a strict deadline, that one slow operation matters even if the average is fine.
- Big numbers. Adding two integers is O(1) only while they fit in a machine word. Python integers grow without limit, so adding two numbers with d digits costs O(d).
- Allocation and garbage collection. Creating objects costs time that Big O rarely counts.
Other things the model does not capture
- Worst case versus typical case. A quadratic worst case may never occur on your data. Quicksort with a good pivot rule is a standard example.
- Parallelism. Two O(n) algorithms can differ by a factor equal to your core count if only one can be split across threads.
- Branch prediction. A loop with an unpredictable branch can run slower than a longer loop whose branch is predictable.
- Galactic algorithms. Some algorithms have the best known asymptotic bound, but their constants are so large that they beat simpler methods only on inputs bigger than anything that fits in memory. Some fast matrix multiplication algorithms are in this category.
How to decide in practice
Use Big O as a first filter, then measure. A workable process:
- Estimate the realistic range of n, including the largest case you must support.
- Eliminate algorithms whose growth rate is clearly too steep for that range. O(2^n) at n = 60 is out, and so is O(n^2) at n = 10^7.
- Among the survivors, prefer the simplest one.
- Benchmark with realistic data on realistic hardware. Use a profiler to find where time actually goes before you optimize.
- Re-measure after each change.
Summary of the limits
| Limit of Big O | What to do |
|---|---|
| Hides constant factors | Benchmark at your real n |
| Hides lower-order terms | Compute the full cost expression when n is moderate |
| Treats all steps as equal | Separate memory, disk, and network costs |
| Ignores memory layout | Prefer contiguous data and sequential access |
| Describes growth, not latency spikes | Check worst single-operation cost when deadlines matter |
Exercise
Algorithm A performs 50n log2(n) steps, and algorithm B performs n^2 steps. Use n = 100 and n = 500 to say which one is cheaper at each size, and explain what this shows about relying on Big O alone. (Use log2(100) ≈ 6.64 and log2(500) ≈ 8.97.)
Show answer
At n = 100, A costs 50 × 100 × 6.64 ≈ 33,200 steps and B costs 10,000, so B is cheaper. At n = 500, A costs 50 × 500 × 8.97 ≈ 224,250 steps and B costs 250,000, so A is slightly cheaper. A is O(n log n) and B is O(n^2), yet B wins at n = 100. The crossover lies a little below n = 500, so Big O only predicts the winner for large enough n. For smaller inputs the constant factor 50 decides the outcome, and you need to measure or compute the full expression.
Exercise
A program sums every element of a large 2D array stored row by row in contiguous memory. Version 1 loops over rows in the outer loop. Version 2 loops over columns in the outer loop. Both are O(rows × columns). Which is likely faster in a language like C, and why?
Show answer
Version 1 is likely faster. It reads consecutive addresses, so each cache line it loads supplies several useful values and the hardware prefetcher can predict the next access. Version 2 jumps by a whole row length on every step, so it often misses the cache and waits on main memory. The operation count is the same, which is why Big O does not distinguish them.