Sub topic 5
Fixing the algorithm and the data structure first
This chapter assumes you can read cProfile output (tottime, cumulative time, callers) and that you know Python lists, dicts, and sets. After profiling, the biggest wins usually come from changing how much work the program does, not from making each step cheaper.
Why the algorithm comes first
Big-O describes how work grows with input size. A function that does 10 operations per item for n items runs in time proportional to n. A function that compares every item with every other item runs in time proportional to n². Micro-optimizations change the constant factor. A better algorithm changes the growth rate, so its benefit increases as the data grows.
A profile often shows this pattern: one function has a very high tottime, and it is called from a loop. Before you rewrite the function body, ask whether the loop or the container is the real problem.
A common culprit: membership tests on a list
The expression x in some_list scans the list from the start until it finds a match. That takes time proportional to the list length. For a set or dict, the same test hashes the value and jumps to its slot, which takes roughly constant time 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. The exact times depend on your machine, but the set is typically orders of magnitude faster here.
Worked example: finding duplicates
Suppose a profile shows find_duplicates dominating the run time.
def find_duplicates_slow(values):
duplicates = []
for i, value in enumerate(values):
if value in values[:i] and value not in duplicates:
duplicates.append(value)
return duplicates
def find_duplicates_fast(values):
seen = set()
duplicates = set()
for value in values:
if value in seen:
duplicates.add(value)
else:
seen.add(value)
return list(duplicates)
data = list(range(2_000)) + list(range(0, 2_000, 2))
assert sorted(find_duplicates_slow(data)) == sorted(find_duplicates_fast(data))The slow version slices the list on every iteration and scans the slice, so it does O(n²) work. The fast version visits each value once and uses set lookups, so it does O(n) work. The assert confirms both return the same answer, but note that the fast version does not preserve the order of first duplication. If order matters, use a dict as the second container, because dicts keep insertion order.
Choosing a data structure for the access pattern
| Need | Poor fit | Better fit |
|---|---|---|
| Test whether an item exists | list | set or dict |
| Look up a value by key | list of pairs | dict |
| Remove from the front repeatedly | list (`pop(0)` shifts every item) | `collections.deque` |
| Keep items sorted and search them | re-sorting each time | `bisect` on a sorted list |
| Count occurrences | manual dict updates | `collections.Counter` |
A workflow for the change
Common errors
- Converting a list to a set inside the loop. Building the set costs O(n), so doing it on every iteration cancels the gain. Build it once, outside.
- Testing with tiny inputs. At n = 20 the list and set can look the same. Time with realistic sizes.
- Assuming sets keep order or allow duplicates. They do neither.
- Using unhashable items. Lists cannot go in a set. Convert them to tuples first.
Exercise
A profile shows a loop that runs if name in allowed_names 100,000 times, where allowed_names is a list of 5,000 strings that never changes. What is the fix, and where should it go?
Show answer
Build allowed_set = set(allowed_names) once before the loop and test name in allowed_set inside it. A set lookup takes roughly constant time on average, while the list scan takes time proportional to 5,000 items. Creating the set inside the loop would repeat the O(n) build cost and remove the benefit.