Where time is really lost, why half of the well-known micro-optimizations stopped working after 3.11, and in what order to pull the levers so as not to rewrite what is already fast.
Commit to an output and a reason before you open the answer.
import timeit
N = 1_000_000
variants = {
"loop + append": f"r = []\nfor i in range({N}): r.append(str(i))",
"comprehension": f"r = [str(i) for i in range({N})]",
"map": f"r = list(map(str, range({N})))",
}
for name, stmt in variants.items():
print(f"{name:14} {min(timeit.repeat(stmt, number=1, repeat=7)):.3f} s")loop + append 0.082 s
comprehension 0.077 s
map 0.086 sThe difference is within the noise. The classic advice “replace the loop with a comprehension” no longer gives anything.import math
vals = list(range(300_000))
# [math.sqrt(v) for v in vals]
# s = math.sqrt; [s(v) for v in vals]via the module: 0.346 s
local reference: 0.297 sThe old hoisting trick still works — but it gives 14%, not multiples.import timeit
setup = '''
import random
random.seed(0)
data = [random.randrange(3000) for _ in range(9000)]
'''
by_list = '''
result = []
for x in data:
if x not in result:
result.append(x)
'''
by_set = '''
seen, result = set(), []
for x in data:
if x not in seen:
seen.add(x)
result.append(x)
'''
print(f"list lookup: {min(timeit.repeat(by_list, setup, number=10, repeat=5)):.3f} s")
print(f"set lookup: {min(timeit.repeat(by_set, setup, number=10, repeat=5)):.4f} s")list lookup: 0.568 s
set lookup: 0.0040 s154 times. The same code, a different data structure.import timeit
setup = '''
class A:
def __init__(self): self.x = 1
class B:
def __init__(self): self.x = 1
class C:
def __init__(self): self.x = 1
mono = [A() for _ in range(30_000)] # one type at the access site
poly = [A(), B(), C()] * 10_000 # three types mixed together
def total(objs):
t = 0
for o in objs:
t += o.x
return t
total(mono); total(poly) # warm-up: the inline cache gets to specialize
'''
print(f"one class: {min(timeit.repeat('total(mono)', setup, number=100, repeat=7)):.3f} s")
print(f"three classes: {min(timeit.repeat('total(poly)', setup, number=100, repeat=7)):.3f} s")one class: 0.063 s
three classes: 0.089 sIdentical code, a difference of 1.4 times.All the mechanisms were covered in earlier lessons. Here: the order in which to apply them, and why it is that order.
The cost of an operation in Python is determined not by the line of code but by how many objects it creates and how many times it goes back into the interpreter.
The order of the levers is fixed and goes by decreasing return: algorithm → data structure → leaving the object model → leaving the interpreter → rewriting.
Snippet C. Replacing a list with a set in a membership check gives 154 times — more than any micro-optimization, any JIT and any rewrite in C put together. The reason is in lesson 03: a list knows nothing about its elements except their addresses, so in can only be a scan.
Hence the first rule: before optimizing code, check whether it has a loop inside a loop. The sign is in, index, remove on a list inside a traversal, or a nested pass over the same collection.
From lesson 03: a million integers in a list are 36 MB and a million objects; in numpy, 8 MB in one block. From lesson 04: __slots__ removes a third of the memory per object. From lesson 13: a generator instead of a list means constant memory instead of linear.
All of this is one and the same lever: stop creating objects where data is what you need. It works by orders of magnitude because it removes not operations but entities.
Snippet A is an important negative result. The advice “a list comprehension is faster than a loop with append” once gave a noticeable gain; now the difference is seven percent, that is, noise. The reason is in lesson 04: since 3.11 the interpreter specializes instructions based on actual execution, and the gap between forms of writing has narrowed.
Snippet B shows that not everything is dead: moving math.sqrt into a local variable gives 14% — an attribute lookup in a module still costs more than reading a local. But it is 14%, not multiples, and it is worth applying only in a proven hot spot.
The practical conclusion: any performance advice older than 3.11 has to be rechecked by measurement. Half of it describes an interpreter that no longer exists.
Snippet D is something you will not find in the advice. The same loop over objects of one class and over a mix of three differs by a factor of 1.4, because the inline cache holds one type version and misses on a heterogeneous collection (lesson 04).
Hence a non-obvious technique: splitting a mixed collection into homogeneous ones and processing them in turn can be faster than one pass over the mix. A profiler will not suggest this — it will show time in the loop, and the cause is visible only from the mechanism.
| lever | typical return | from |
|---|---|---|
| algorithm and data structure | tens and hundreds of times | lessons 03, 05 |
leaving the object model: numpy, array, generators, __slots__ | a few to tens of times | lessons 03, 04, 13 |
| leaving the interpreter: threads on C code, asyncio on waits | up to the number of cores, or an order of magnitude | lessons 15, 19, 20 |
| homogeneity of data, caching | a few times | lessons 04, 08 |
| micro-optimizations of how code is written | percent | this lesson |
| rewriting in C or Rust | multiples, but at a high price | lesson 16 |
Each row is an order of magnitude cheaper than the next and often settles the question. Going from the bottom up is the most common mistake in optimizing Python.
A profiler distorts what it measures. cProfile adds overhead to every call, so it overstates the share of functions that are called often and briefly. It is fine for relative comparison, not for absolute numbers; sampling profilers like py-spy are more honest.
A microbenchmark almost always lies. The CPU cache, interpreter specialization, the absence of real data — all of this makes an isolated measurement unlike production. A guideline: timeit for comparing two forms of writing, the real load for decisions.
The numbers are tied to the version 🔧. 3.11 narrowed the gap between forms of writing, 3.12 and 3.13 continued, and the JIT in 3.13+ will change it again. Everything measured here is worth re-measuring on your version.
Root R2: attributes are resolved at runtime. For twenty years this was expensive — every attribute access and every call went through the full lookup path. That is exactly where the “Python is slow” reputation comes from, and it was deserved.
It was paid off in 3.11 by the Faster CPython project: the specializing adaptive interpreter (PEP 659) learned to remember the result of a lookup right in the bytecode stream, and frames became cheaper. The language mechanism did not change — what changed is that repeated execution does not perform it in full.
The practical consequence for this lesson: a significant part of the accumulated folklore describes the interpreter before 3.11. Advice about hoisting, about comprehensions instead of loops, about local variables — all of it was measured on a machine that no longer exists, and has to be rechecked.
The order of the levers is the optimization hierarchy from C, shifted one level up. There it is the algorithm first, then data layout and the cache, then vectorization, and only at the end assembly. Here it is exactly the same ladder, but the first rungs are different: first the algorithm, then leaving the object model (the analogue of “layout”), then leaving the interpreter (the analogue of “vectorization”), and only at the end rewriting in C.
It is also useful that the top rung is the same in both languages: measure before you touch. The difference is that in C the profile shows where the hot code is, while in Python it also shows how many objects are created — and that second number is usually more important than the first.
Questions that come up on their own if you read closely. The answer is under the question.
Because it described an interpreter that no longer exists.
Advice like “a list comprehension is faster than a loop”, “move the dot out of the loop”, “locals are faster than globals” was born in an era when every bytecode instruction cost a full lookup: an attribute meant three dictionaries, a global name two. Removing one access meant removing a noticeable share of the work.
Since 3.11 specialization is at work (PEP 659): after warm-up an instruction rewrites itself for the observed type and keeps the observation in an inline cache right in the bytecode stream (lesson 23). The repeated lookup was replaced by one comparison of the type version — and the gap between forms of writing collapsed.
loop + append 0.082 s
comprehension 0.077 s ← 7%, that is, noise
map 0.086 s
What has not become obsolete: everything that removes not operations but entities. The complexity class (154× from replacing a list with a set), leaving the object model (numpy, array, generators, __slots__), leaving the interpreter (threads on C code). These levers worked twenty years ago and work now, because they are about the number of objects created, not about the form of writing.
The practical rule: performance advice has a shelf life, and it is determined by the publication date. Everything older than 3.11 has to be rechecked by measurement — including the numbers in this canon, if you are reading it on another version.
Next you have to answer the second question, which the profile does not ask: is the time going into the work, or into organizing it?
An estimate from lesson 23: a bytecode instruction is about 6 ns, a function call 27 ns. So a function of ten lines of simple code is roughly a hundred instructions, that is, 600 ns plus the call. If the profile shows ten microseconds, the time is not going into interpretation, and micro-optimizations will not help there.
From here there are three different questions and three different tools:
cProfile shows ncalls. It often turns out that the function is cheap but called a million times from a loop inside a loop — and what needs fixing is not the function but the algorithm.tracemalloc before and after. Allocation is the second-largest source of time after the algorithm, and in a time profile it is smeared out and invisible.print_callers in pstats. The answer “it is called from where it should not be” comes up more often than “it is slow”.python -m cProfile -s tottime script.py | head -20
# tottime is the function's own time without nested calls; sort by it,
# otherwise main will always be at the top
And on a live process — py-spy top --pid: no restart, almost no overhead, it reads frames straight from the memory of another process (lesson 23).
Because the effect appeared only in 3.11 and follows not from the code but from the mechanism of inline caches.
Every attribute access site keeps in its cache the version of the type that was seen there. As long as the same type keeps arriving — one comparison and direct access. Different types arrive — the cache misses, and the instruction deoptimizes back into the generic one.
one class: 0.063 s
three classes: 0.089 s ← 1.4× with completely identical code
Hence a technique that is not in the advice: splitting a mixed collection into homogeneous ones and processing them in turn can be faster than one pass over the mix. A profiler will not suggest this — it will show time in the loop, and the cause is visible only from the mechanism.
Where this occurs in reality. A list of tree nodes of different classes. A collection of events where each event type is its own class. ORM objects loaded from different tables into one list. Polymorphism, which is customarily praised, is paid for here in time.
And the flip side: it can be seen only with the disassembler, and there is no “did the specialization work” API:
import dis
dis.dis(hot_function, adaptive=True)
# LOAD_ATTR_INSTANCE_VALUE — the specialization held
# LOAD_ATTR or LOAD_ATTR_ADAPTIVE — it did not
The effect is entirely 🔧: on 3.10 it did not exist, and on 3.13 with the JIT the picture is different again.
array, generators, __slots__), leaving the interpreter — up to the number of cores, and only at the end micro-optimizations that give percent. Half of the well-known advice is obsolete: a list comprehension against a loop with append is six percent, that is, noise, because since 3.11 the interpreter specializes instructions based on actual execution. Hoisting still works, but gives 14%, not multiples. And there is an effect that is not in the advice: a homogeneous collection is traversed 1.4 times faster than a mix of classes, because the inline cache holds one type version. Any advice older than 3.11 has to be rechecked by measurement.C and C++ optimize for the cache, branches and vectorization: the work is already compiled, the bottleneck is memory access. In Python there is nothing to fight at that level while the data lies around as objects: any operation costs orders of magnitude more than a cache miss. That is why the first lever here is not layout but getting away from objects: numpy is precisely a way back into the world where layout matters again.
Tellingly, after moving to numpy, the advice from C starts to work literally: contiguity, element type, batch size, vectorization — the same optimization as in C, because the data finally lies the same way.
Java and JavaScript with their JITs solve exactly the task CPython started solving in 3.11: specializing dynamic code based on actual execution. V8 arrived at inline caches in 2008, CPython in 2022. The gap explains both the lag in speed and why it is shrinking.
A classic that is impossible to notice from inside the task: optimization without a profile.
# “This parser is surely slow, it's in a loop”
def parse_line(line): # rewritten, made three times faster
...
A profile taken afterwards shows that parse_line took four percent of the total time. Making it three times faster gave the service three percent. The other ninety-six went into waiting on the database, which nobody asked about.
Review always lets it through: the diff improves the code, the tests are green, the function benchmark honestly shows a speed-up. The mistake is not in the code but in having chosen it.
The right order starts not with code but with answering the question “where does the time go”:
# on a live process, without a restart and with almost no overhead
py-spy top --pid 12345
py-spy dump --pid 12345 # where the threads are standing right now
# locally, to compare variants
python -m cProfile -s tottime script.py | head -20
Read tottime, not cumtime: the first is the time in the function itself, the second includes its calls. The candidate for optimization is the one with a large tottime, not the one that looks complicated.
And check that you are bound by the processor at all: if py-spy shows threads in read or waiting on a driver, optimizing Python is pointless — that is a problem from lesson 20, not from this one.
The rule: the upper bound of the gain equals the share of time spent in this code. Twenty percent means that even an infinite speed-up gives twenty percent — and that has to be counted before you start.
The order matters more than knowing the tricks: the question is almost always closed at the first or second step.
Step 1 — where the time goes. py-spy in production or cProfile locally. The answer “waiting” moves the problem to lesson 20 and ends this one.
Step 2 — algorithm and structures. Look for in on a list inside a loop, nested passes, recomputing the same thing. The return is hundreds of times.
seen = set() # instead of if x not in result
result = [x for x in items if not (x in seen or seen.add(x))]
Step 3 — get away from objects. Homogeneous numbers into array or numpy; intermediate lists into generators; masses of small objects onto __slots__. The return is a few to tens of times, plus memory.
Step 4 — leave the interpreter. The measurement from lesson 19: sequential against two threads. It sped up — scale with threads; it did not — look at processes, taking the volume of transfer into account.
Step 5 — only now micro-optimizations and rewriting. Caching with lru_cache (lesson 08), hoisting in a proven hot loop, the data homogeneity from consequence 4. And an extension in C or Rust — with the full cost counted, as in lesson 16.
| step | what it gives |
|---|---|
| data structure | 140× on deduplication |
| numpy instead of a list | 9× in memory, orders of magnitude in time |
| threads on C code | 1.9× on two cores |
| homogeneous collection | 1.4× |
| hoisting | 14% |
| comprehension instead of a loop | 6%, that is, noise |
The numbers are from this canon's measurements on 3.11. Note the spread: there are four orders of magnitude between the top and the bottom of the table, and that is exactly why the order of the steps matters more than their content.
Run the snippets and check them against your prediction. Then:
import dis
class P:
def __init__(self): self.x = 1
p = P()
def f(o): return o.x
dis.dis(f, adaptive=True)
for _ in range(200): f(p)
dis.dis(f, adaptive=True)
# What changed in the instructions after warm-up?
import tracemalloc
tracemalloc.start()
data = [{"i": i} for i in range(100_000)]
print(tracemalloc.get_traced_memory())
# How much memory does the hot path cost? This is the second most important question after “where does the time go”.
import timeit
print(timeit.timeit("sum(range(1000))", number=10_000))
print(timeit.timeit("total=0\nfor i in range(1000): total+=i", number=10_000))
# By how many times? Why does the built-in function win?
And one check from the terminal — how much of the startup time goes into imports (lesson 17):
python -X importtime -c "import myapp" 2>&1 | sort -k2 -nr | head
The last question leads to a general principle: any work done entirely inside one built-in function does not go back into the interpreter on every iteration — and so it is cheaper than a loop doing the same thing.
Lib/cProfile.py and Lib/pstats.py. It is worth reading pstats once to stop seeing a profile as a wall of text: there are only a few sorting and filtering methods, and print_callers with print_callees answer the question “who calls this” better than reading the code.
Lib/dis.py. The adaptive=True parameter shows specialized instructions — the only way to see whether the optimization from lesson 04 was applied to your code. Useful on a hot loop: if the instructions stayed generic, the specialization failed, and it is worth understanding why.
Lib/timeit.py. Note that by default it disables the garbage collector and takes the minimum of the runs rather than the mean. Both decisions are explained in the source, and they explain why timeit gives better numbers than a home-made measurement with time.perf_counter.
From L1 you know the order of the levers. Here: what the cost is made of.
Reference points for 3.11, orders of magnitude rather than exact numbers:
| operation | order |
|---|---|
| arithmetic on small ints | tens of nanoseconds |
| attribute access after specialization | a few nanoseconds |
| calling a Python function | tens of nanoseconds |
| creating an object | hundreds of nanoseconds, plus work for the collector |
| dictionary lookup by string | tens of nanoseconds, the hash is cached |
The main conclusion from the table: creating an object costs more than any single operation on objects that already exist. That is why the first question when optimizing a hot loop is not “which operations to make faster” but “which objects not to create”: intermediate lists, temporary strings, wrappers.
On specialization. An instruction specializes after a few executions and is invalidated when the class changes. You can see it like this:
import dis
def f(o): return o.x
class A:
def __init__(self): self.x = 1
a = A()
for _ in range(100): f(a)
dis.dis(f, adaptive=True)
# → LOAD_ATTR_INSTANCE_VALUE instead of the generic LOAD_ATTR
If the instruction stayed generic after warm-up, the specialization failed — the typical reasons are listed in Python/specialize.c: too many different types in one place, dynamic changes to the class, unusual descriptors. That is the mechanism of consequence 4.
Tag v3.11.15.
Python/specialize.c — how the decision to specialize an instruction is made, and for what reasons it fails. The list of failure reasons is useful in itself as a checklist.Python/ceval.c — the interpreter loop: you can see that specialized instructions are separate branches.Objects/frameobject.c — frames, which became cheaper in 3.11; hence the drop in the cost of a call.obj.x, end to end — inline caches and the homogeneity effect