What are practical ways to speed up a genuinely hot Python loop once profiling has confirmed it is the bottleneck?
Answer
Profile first, and re-profile after every change — intuition about what is slow is frequently wrong, and an optimization that helped on one Python version can be neutral or even counterproductive on a newer one, since modern specializing CPython (3.11+) already optimizes some patterns internally. The most reliable wins are usually algorithmic: reducing the amount of Python-level work done per item, replacing a manual loop with a built-in implemented in C where the semantics genuinely match (`sum()`, `any()`, list comprehensions instead of a hand-written append loop), moving work out of the loop when it produces the same result every iteration, and batching numeric work with a vectorized library like NumPy instead of looping in pure Python. Older micro-tricks like prebinding a frequently-used method or global to a local name before a hot loop can still help in some cases, but their benefit is version- and workload-dependent rather than a guaranteed standard win — always benchmark a specific change on the target Python version rather than assuming it helped.
Strong answer includes
- profile first, and re-profile after each change rather than assuming a fix helped
- algorithmic changes and built-in C implementations are the most reliable wins
- older micro-optimization tricks are version- and workload-dependent, not guaranteed wins on modern specializing CPython
Practical example
Replacing
result = []
for x in data:
result.append(transform(x))with
result = [transform(x) for x in data]is both more idiomatic and measurably faster, because comprehensions avoid the repeated attribute lookup for `.append` .