Skip to content

Lesson 4 of 9 · 20m

Algorithmic and Interpreter-Aware Wins

The fastest Python is usually less work, not cleverer work: better complexity, fewer object allocations, and using builtins whose loops live in C.

New performance-minded Python developers often reach for threads before checking complexity. That is backwards. If the algorithm does ten times too much work, no concurrency model will save it; it will only do the wrong work in parallel.

The first optimization pass is boring: reduce operations, reduce allocations, and move loops into implemented-in-C primitives.

Complexity beats constants

A membership check tells the story cleanly:

# accidental O(n) per lookup
allowed = ["alpha", "beta", "gamma"] * 1000
if name in allowed:
    ...

# deliberate O(1)-average lookup
allowed = {"alpha", "beta", "gamma"}
if name in allowed:
    ...

The fix is rarely exotic: use set or dict membership instead of repeated list scans, collections.deque for pops from the left, heapq for repeated smallest-item selection, bisect over a sorted list, or incremental aggregation instead of recomputing totals. A profiler line saying <listcomp> is expensive is often the symptom; the cause is that the comprehension sits inside another loop.

The interpreter tax is per operation

Python bytecode dispatches rich objects. Even simple arithmetic carries allocation and method lookup costs. The practical conclusion is not "avoid Python"; it is "make each bytecode do more meaningful work."

# more interpreter turns
total = 0
for row in rows:
    total = total + row.amount

# the loop over addition lives closer to C
total = sum(row.amount for row in rows)

Builtins such as sum, min, max, any, all, map, and comprehensions are not magic, but they are usually tighter than hand-written bytecode. Binding a method locally (append = out.append) also helps in measured hot loops — and makes cold code uglier, so reserve it for code the profiler proved matters.

Allocation is work even when the algorithm is fine

String concatenation in a loop is the classic example because immutable strings force repeated copying:

# avoid
text = ""
for part in parts:
    text += part

# prefer
text = "".join(parts)

The same principle appears with repeated JSON encoding, tiny temporary dictionaries, unnecessary sorting, and constructing objects only to read one field. Sometimes the fastest change is changing an interface to pass the one field that is actually used.

Field notes

  • Measure before and after every "obvious" fix. Big-O reasoning tells direction, not production impact.
  • Keep readability as the default. Interpreter microtricks are justified only in measured hot loops.
  • Do not cache everything. Caches trade memory and invalidation complexity for CPU.
  • A 10x algorithmic improvement usually survives the next rewrite; a 5% bytecode trick often does not.

Was this lesson helpful?

Sign in to rate