Sub topic 5
Fixing the algorithm and the data structure first
This chapter assumes you can read a cProfile report and tell tottime from cumulative, and that you can time a snippet with timeit or time.perf_counter. You should also know how lists, dicts, and sets behave in everyday code. Here you will use a profile to decide whether the code needs a better algorithm or data structure. You will then make the change and confirm the gain.
Why the algorithm comes first
A micro-optimization such as caching an attribute lookup or swapping a loop for a comprehension usually gains a constant factor, often 10% to 2x. An algorithm change alters how the running time grows with input size. Going from quadratic to linear on 10,000 items is a roughly 10,000x reduction in work, and the gap widens as the input grows.
Two consequences follow:
- A fast constant factor cannot rescue a slow growth rate. Quadratic code that is fast on 1,000 rows can take minutes on 1,000,000.
- Tuning idioms inside a quadratic loop only speeds up code that should not be there.
Recognizing the signal in a profile
Your profile gives clues that point to an algorithm problem rather than a slow line:
- A small function with a huge
ncallsand a largetottime. A "find" helper called 5,000 times that each scan 5,000 items will dominate. - Built-ins such as
list.index,list.count,list.remove,list.insert, orinon a list that account for most of the time. - Time that grows faster than input size. Time the function at n, 2n, and 4n. Doubling the input roughly quadruples the time for quadratic code.
The third check is cheap and reliable, so run it before you rewrite anything.
Membership: list versus set
The most common fix is replacing a list with a set when you only ask "is this value present?". The in operator on a list compares items one by one, which is O(n). On a set it hashes the value and jumps to a bucket, which is O(1) on average.
import timeit
items_list = list(range(10_000))
items_set = set(items_list)
list_time = timeit.timeit("9_999 in items_list", globals=globals(), number=1_000)
set_time = timeit.timeit("9_999 in items_set", globals=globals(), number=1_000)
print(f"list membership: {list_time:.4f}s")
print(f"set membership: {set_time:.4f}s")The value 9_999 is the last element, which is the worst case for the list. Searching for 0 would make the list look fast, because the scan stops at the first item. When you benchmark a data-structure change, test the cases that match your real data: hits, misses, and typical positions.
A worked example: finding common values
This function returns the values of a that also appear in b. The first version scans the list b for every element of a. The second builds a set once.
import random
import time
def common_quadratic(a, b):
result = []
for x in a:
if x in b: # b is a list: a linear scan on every iteration
result.append(x)
return result
def common_linear(a, b):
b_set = set(b) # one O(len(b)) pass
return [x for x in a if x in b_set]
random.seed(1)
a = random.sample(range(1_000_000), 5_000)
b = random.sample(range(1_000_000), 5_000)
for func in (common_quadratic, common_linear):
start = time.perf_counter()
result = func(a, b)
elapsed = time.perf_counter() - start
print(f"{func.__name__}: {elapsed:.4f}s, {len(result)} matches")
assert common_quadratic(a, b) == common_linear(a, b)Exact times depend on your machine, but the second version is typically hundreds of times faster at this size. The assert matters. After any rewrite, check that the new code returns the same answer as the old one before you trust the timing.
Notice that common_linear keeps the order of a. The set is used only for lookups, so the output stays the same.
Other swaps that change the growth rate
Lists are a good default, but several operations on them are linear. The standard library has structures built for these cases.
| Task | Slow choice | Better choice | Cost change |
|---|---|---|---|
| Is this value present? | `x in some_list` | `x in some_set` or dict | O(n) to O(1) average |
| Remove from the front | `list.pop(0)` | `collections.deque.popleft()` | O(n) to O(1) |
| Find a value in sorted data | linear scan | `bisect.bisect_left` | O(n) to O(log n) |
| Count occurrences of every item | `list.count` per item | `collections.Counter` | O(n·k) to O(n) |
| Find a record by key | loop over a list of records | dict keyed by that field | O(n) to O(1) average |
| Top k items | `sorted(data)[:k]` | `heapq.nlargest(k, data)` | O(n log n) to O(n log k) |
Here is the queue case. Popping from the front of a list shifts every remaining element left, so draining a list this way is quadratic.
import timeit
n = 50_000
list_time = timeit.timeit(
"while q: q.pop(0)",
setup=f"q = list(range({n}))",
number=1,
)
deque_time = timeit.timeit(
"while q: q.popleft()",
setup=f"from collections import deque; q = deque(range({n}))",
number=1,
)
print(f"list.pop(0): {list_time:.4f}s")
print(f"deque.popleft(): {deque_time:.4f}s")For sorted data, bisect finds a position in logarithmic time. This helper tests membership without a set, which is useful when the data must stay sorted or memory is tight.
from bisect import bisect_left
def contains_sorted(sorted_items, value):
i = bisect_left(sorted_items, value)
return i < len(sorted_items) and sorted_items[i] == value
data = [2, 3, 5, 7, 11, 13]
print(contains_sorted(data, 7)) # True
print(contains_sorted(data, 8)) # FalseFor counting, Counter makes one pass over the data:
from collections import Counter
words = ["red", "blue", "red", "green", "blue", "red"]
# Slow: words.count scans the whole list once per distinct word
slow = {w: words.count(w) for w in set(words)}
# Fast: a single pass
fast = Counter(words)
assert slow == dict(fast)
print(fast.most_common(2))Choosing a structure
Edge cases and costs
A faster structure is not free. Check these before you commit to a change.
- Building the set costs O(n). If you test membership only once or twice,
x in some_listis cheaper than creating a set. The set pays off when the same collection is queried many times. - Build it once, outside the loop. Writing
if x in set(b)inside the loop rebuilds the set on every iteration and gives you the slowest version of both approaches. - Elements must be hashable. Lists and dicts cannot go into a set. Convert records to tuples, or key a dict on a stable field such as an ID.
- Sets drop duplicates and do not keep order. If you need either, keep the original list and use the set only as an index beside it.
- Equality and hash must agree. For custom classes, objects that compare equal must have the same hash. Define
__eq__and__hash__together, and do not mutate fields that feed the hash while the object is in a set. - Memory increases. A set or dict of the same items takes noticeably more memory than a list. A later chapter shows how to measure this with
tracemalloc. - Small inputs may not improve. For a dozen items, a list scan is often as fast as hashing. Measure at your real size, not at the size of your test fixture.
- Sorted lists have a catch.
bisect.insortfinds the position quickly but still shifts elements on insertion, so frequent inserts into a large list stay O(n). A dict or set suits that workload better.
Confirming the gain
Use the same loop each time you change an algorithm:
- Profile and identify the function whose
tottimeor call count dominates. - Time it at two or three input sizes to see how it grows.
- Pick the structure or algorithm that matches how the data is used.
- Keep the old version as a reference and assert that both return identical results.
- Time the new version at the same sizes and confirm that both the absolute time and the growth rate improved.
- Re-profile the whole program. The hot spot often moves, and the next target may be somewhere else.
Exercise
A function filters 20,000 log lines by checking whether each line's user ID appears in a list of 20,000 blocked IDs: [line for line in lines if line.user_id in blocked]. The profile shows the list comprehension taking 95% of the runtime. What change would you make, and what must you check afterwards?
Show answer
Build a set once before the comprehension, with blocked_set = set(blocked), and test line.user_id in blocked_set. That turns about 20,000 × 20,000 comparisons into 20,000 hash lookups plus one O(n) build. Afterwards, check that the output is identical to the list version, that the IDs are hashable (strings and ints are), and that you re-measured at the real input size and re-profiled to find the next hot spot. The original blocked list can stay if order or duplicates matter elsewhere.