Sub topic 14
When Big O is not enough: constants, caches, and small inputs
This chapter assumes you can read the complexity classes from O(1) to O(n!), simplify cost expressions, and analyze loops and recursion. Big O answers one question: how does cost grow as n becomes large? It does not tell you which of two programs is faster on the input you have. Three things sit outside the notation: constant factors, memory behavior, and small n.
Constants are hidden by design
Big O drops constant factors, so 100n and n are both O(n). An algorithm that does 100n steps is still 100 times slower than one that does n steps. Asymptotics only promise that for large enough n, a lower growth rate wins. Consider 100n against n². The linear one wins only when n is above 100. If your inputs are always 50 items, the quadratic one is faster.
Real libraries use this fact. Many sort implementations switch to insertion sort, which is O(n²), once a sub-array is small. Insertion sort has very little overhead per step, so it beats O(n log n) merge sort on short inputs.
Measuring the crossover
The program below times both sorts on growing inputs. The exact crossover depends on your machine and Python version, so run it yourself.
import random
import timeit
def insertion_sort(items):
items = list(items)
for i in range(1, len(items)):
key = items[i]
j = i - 1
while j >= 0 and items[j] > key:
items[j + 1] = items[j]
j -= 1
items[j + 1] = key
return items
def merge_sort(items):
if len(items) <= 1:
return list(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
for n in (4, 16, 64, 256, 1024):
data = random.sample(range(n * 10), n)
runs = max(1, 20000 // n)
t_ins = timeit.timeit(lambda: insertion_sort(data), number=runs) / runs
t_mrg = timeit.timeit(lambda: merge_sort(data), number=runs) / runs
print(f"n={n:5d} insertion={t_ins * 1e6:9.1f} us merge={t_mrg * 1e6:9.1f} us")On small n the insertion column is usually lower. As n grows, its time climbs roughly fourfold each time n doubles, while merge sort's climbs only slightly more than twofold.
Caches and memory layout
Big O usually counts operations as if each costs the same. Real memory is not like that. A CPU reads memory in blocks called cache lines, and reading data near what you just read is much faster than jumping around.
| Access pattern | Complexity | Typical behavior |
|---|---|---|
| Sum a 2D array row by row, in storage order | O(n²) | Fast: sequential reads reuse cache lines |
| Sum the same array column by column | O(n²) | Often slower: each read can miss the cache |
| Array of values | O(n) scan | Contiguous, cache-friendly |
| Linked list | O(n) scan | Nodes scattered in memory, more cache misses |
Both traversals do the same number of additions, so Big O cannot separate them. The same effect is why a linear scan of a small array can beat a hash table or a balanced tree lookup that is O(1) or O(log n) on paper.
Other costs the notation skips
- Hidden operation costs. String concatenation, hashing, and comparison are each treated as one step, but they take longer on longer keys.
- Allocation and garbage collection. Creating many small objects adds time that does not appear in the operation count.
- Interpreter overhead. In Python, a built-in
sortedruns in compiled code. A hand-written O(n log n) sort in Python can lose to it by a large factor.
A practical rule
Use Big O to rule out approaches that will fail at scale, such as an O(2ⁿ) search on 60 items. Use measurement to choose among approaches whose growth rates are close or whose inputs are small.
Exercise
Algorithm A takes 5n² steps and algorithm B takes 200n steps. For which values of n is A faster, and why does Big O not tell you this?
Show answer
A is faster when 5n² < 200n, which means n < 40. At n = 40 they are equal, and for larger n B is faster. Big O describes A as O(n²) and B as O(n), which only says B wins for large enough n. It drops the constants 5 and 200, which decide where the crossover point is.