Part 14 / Topic 10 of 11
Common speed-ups
Once the profile shows the slow spot, these fixes cover most real cases. Apply them only where the profile points. Think of a traffic jam: widening every road is a waste; fix the one junction where cars pile up.
1. The right data structure
x in list checks items one by one (slow for big lists). x in set and x in dict jump straight to the answer using the hash (section 2).
blocked = ["[email protected]", "[email protected]"] * 5_000 # 10,000 items
blocked_set = set(blocked) # build once
print("[email protected]" in blocked) # True (scans up to 10,000 items)
print("[email protected]" in blocked_set) # True (one hash lookup)
| Task | Slow | Fast |
|---|---|---|
| "have I seen it?" | list + in |
set |
| look up by key | loop over a list of pairs | dict |
| count things | items.count(x) for every x |
collections.Counter(items) |
| add/remove at the front | list.insert(0, x) / pop(0) |
collections.deque |
2. Local variables and built-ins
Local names are found faster than globals (LOAD_FAST vs LOAD_GLOBAL in the bytecode), and built-ins written in C do the loop for you.
import timeit
prices = list(range(100_000))
def loop_total():
total = 0
for p in prices: # runs several bytecode instructions per item
total += p
return total
def builtin_total():
return sum(prices) # one call, the loop happens in C
print(loop_total() == builtin_total()) # True
print(timeit.timeit(builtin_total, number=20) <
timeit.timeit(loop_total, number=20)) # True
Other C-speed helpers: sorted, min, max, any, all, "".join(parts) (instead of += on strings in a loop), and comprehensions instead of append loops.
3. functools.cache
@cache (Part 10) remembers results, so the same call is never worked out twice. Great for slow, pure functions (same input → same output, no side effects).
from functools import cache
@cache
def shipping_cost(pincode):
print(f" (working out {pincode})") # pretend this is slow
return 40 if pincode.startswith("41") else 80
for pin in ["411001", "110001", "411001", "411001"]:
print(pin, shipping_cost(pin))
print(shipping_cost.cache_info().hits) # 2
Output:
(working out 411001)
411001 40
(working out 110001)
110001 80
411001 40
411001 40
2
4. Avoid repeated work
Move work that gives the same answer out of the loop.
orders = [("Pune", 1760), ("Delhi", 540), ("pune", 2999)]
allowed = ["PUNE", "MUMBAI"]
# builds the same set again for every order
slow = [amt for city, amt in orders if city.upper() in {c.upper() for c in allowed}]
# build it once
allowed_set = {c.upper() for c in allowed}
fast = [amt for city, amt in orders if city.upper() in allowed_set]
print(slow == fast, fast) # True [1760, 2999]
5. When to reach for NumPy or C
If the profile shows heavy number crunching over millions of values, plain Python loops will stay slow. Then the answer is a library that loops in C: NumPy and pandas (Stage 5, data track). Writing your own C extension is the last resort. First: right data structure, built-ins, caching.
Done here? The practice set for Part 14 — 8 exercises with solutions — is on the part page.