Performance

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.

L1 · 9 minL2 · 10 min📱 phoneverified · CPython 3.11, linux x86-64

1Predict

Commit to an output and a reason before you open the answer.

Snippet A
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 s
The difference is within the noise. The classic advice “replace the loop with a comprehension” no longer gives anything.
Snippet B
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 s
The old hoisting trick still works — but it gives 14%, not multiples.
Snippet C
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 s
154 times. The same code, a different data structure.
Snippet D
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 s
Identical code, a difference of 1.4 times.

2Mechanism

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.

Consequence 1 · the complexity class beats everything else

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.

Consequence 2 · the object model is the second-biggest lever

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.

Consequence 3 · most micro-optimizations are obsolete

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.

Consequence 4 · the homogeneity of data affects speed

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.

Consequence 5 · the order of the levers
levertypical returnfrom
algorithm and data structuretens and hundreds of timeslessons 03, 05
leaving the object model: numpy, array, generators, __slots__a few to tens of timeslessons 03, 04, 13
leaving the interpreter: threads on C code, asyncio on waitsup to the number of cores, or an order of magnitudelessons 15, 19, 20
homogeneity of data, cachinga few timeslessons 04, 08
micro-optimizations of how code is writtenpercentthis lesson
rewriting in C or Rustmultiples, but at a high pricelesson 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.

3Limits of the model

Where this stops holding

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.

4Root

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.

5Analogy

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.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

Why did half of the performance advice stop working?

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.

The profiler pointed at a function — what next?

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:

  • How many times it is called. 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.
  • How many objects it creates. 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.
  • Who calls it. 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).

Why does the homogeneity of data affect speed, when no advice mentions it?

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.

Bottom line. The cost is determined not by the form of writing but by the number of objects created and the number of trips into the interpreter. The order of the levers is fixed and goes by decreasing return: the algorithm and data structure give hundreds of times (a membership check on a set instead of a list — 154×), leaving the object model gives a few to tens (numpy, 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.
From here on — optional
counterfactualC, C++ and JIT languagesWhere the bottleneck is in a compiled language — and why in Python it is somewhere else

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.

🐛 bugOptimized the wrong thingA week of rewriting a function that took four percent of the time

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.

⚡ techniqueGo down the ladder from the topFive steps by decreasing return, each an order of magnitude more expensive than the one before

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.

stepwhat it gives
data structure140× on deduplication
numpy instead of a list9× in memory, orders of magnitude in time
threads on C code1.9× on two cores
homogeneous collection1.4×
hoisting14%
comprehension instead of a loop6%, 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.

💻 terminalCheck it in the terminalThe four snippets plus dis after warm-up, py-spy and tracemalloc

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.

sourcecProfile and disTools that are already installed and that hardly anyone uses

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.

L2What exactly is expensiveThe cost of a call, an allocation and specialization in nanoseconds

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:

operationorder
arithmetic on small intstens of nanoseconds
attribute access after specializationa few nanoseconds
calling a Python functiontens of nanoseconds
creating an objecthundreds of nanoseconds, plus work for the collector
dictionary lookup by stringtens 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.

L3Where this is in the CPython sourcesspecialize.c, ceval.c, PEP 659

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.
  • PEP 659 — the specializing adaptive interpreter; PEP 744 — the JIT, the next step.
connectionsWhere this leadsL03, L04, L15, L20 · contrast with optimization in C
root R2 · Attributes are resolved at runtime, a namespace is a dict
← foundation L03 · Containers — where the 154× and the 9× in memory come from
← foundation L04 · obj.x, end to end — inline caches and the homogeneity effect
← foundation L20 · Concurrency — the “not bound by the processor” branch
↔ contrast Optimization in C: the same ladder, but the first rungs are different
↔ contrast The JIT in V8 and the JVM: the same idea of specialization, fourteen years earlier
not covered here Optimizing database and network queries — most often that is where the real bottleneck is, but it is not about the language
readingFurther readingPEP 659 🟧 · py-spy 🟥 · pstats 🟦

Written by · The Python Canon