Python: CPython internals and performance

What CPython does with your code (bytecode, the specialising interpreter, reference counts, object sizes), how to find where the time goes, how to move the loop out of Python, the experimental JIT measured, and what changed from 3.12 to 3.15; every example run on CPython 3.11 to 3.15 on an Apple M1 Pro. A child of Python: the essentials. Data as of October 2026. Reading: 23 min, plus 6 in closed details.

The idea in one screen

CPython runs your code as bytecode in a loop written in C, and every value is a separate heap object, so a Python loop pays an interpreter step and new objects for every element. Speed comes from moving the loop out of Python (into built-ins, NumPy or native code), and from measuring first to find the one loop that matters.

Fig. 1 is the same reduction over a million floats, the denominator of a softmax: 47.6 ms as a Python loop, 3.2 ms as one NumPy call. Times are the real p2_numpy run of section 4 (CPython 3.14.8, NumPy 2.5.3, Apple M1 Pro); sizes are sys.getsizeof from section 2. The figure draws 8 of the million elements.

  1. A list holds pointers, not numbers. xs is one 8-byte pointer per element, and each pointer leads to a separate float object somewhere on the heap: 24 bytes holding a reference count, a pointer to its type and the 8-byte double. That is 32 bytes per number, against 8. The addresses in the figure are illustrative.
  2. The interpreter visits every element. The C evaluation loop runs the body of for x in xs: s += math.exp(x - m) once per element, follows the pointer, checks the type, and makes 3 new float objects each time (x - m, the exp, the new s). A million times: 47.6 ms.
  3. NumPy keeps the numbers in one buffer. np.exp(a - a.max()).sum() is one Python call; inside it, a.max(), the subtraction, exp and sum are each one tight C loop over a contiguous buffer of 8-byte doubles, with no object per element (the script's comment counts three passes; with a.max() it is four). 3.2 ms.
  4. Same answer, 14.9 times faster. The script asserts that the two sums agree to one part in a million. The speed-up is the per-element interpreter step and the per-element objects removed; section 4 shows it only appears from about a thousand elements up.

Fig. 2 puts the remedies this page measures on one scale. The specialising interpreter (section 1) is already in the "Python loop" time; the JIT (section 5) is off by default.

You need: Python: the essentials (names, objects and the one interpreter). What reference counting and the collector do to a process's memory (pymalloc's arenas, memory that never returns to the OS) is Memory allocators, section 7; profiling a live service with py-spy and flame graphs is Capacity planning and performance.

Bytecode
instructions for CPython's virtual stack machine, compiled from your source and cached in __pycache__/*.pyc.
Evaluation loop
the C loop (Python/ceval.c) that executes bytecode one instruction at a time.
Specialising interpreter
since 3.11, an instruction that keeps seeing the same types is rewritten in place into a faster, type-specific version.
Reference count
the number of references to an object, stored in its header; at zero the object is freed at once.
Cycle collector
the gc module's periodic search for objects that refer only to each other.
Deterministic, sampling profiler
records every call (cProfile), or looks at the stack a few hundred times a second (py-spy, Scalene).
Vectorise
replace a per-element Python loop with one call that loops in C over a typed buffer.
JIT
just-in-time compiler: turns hot code into machine code while the program runs; CPython's is experimental and off by default.

Fig. 2 · Within Python a remedy buys under 3x; moving the loop out buys 15x

Speed-up of each remedy measured on this page, on the same machine (different workloads, named in each bar).

1. Bytecode, and how it rewrites itself while running

CPython, the standard Python, is a C program. It compiles your source to bytecode, instructions for a virtual stack machine (cached in __pycache__/*.pyc), and an evaluation loop in C executes them one by one. The root page's How code runs section follows one line through Python, C++, Rust and JavaScript; this section is CPython's half, seen with the dis module.

Since 3.11 the interpreter is specialising and adaptive (PEP 659): after an instruction has run a few times it is rewritten in place into a version specialised for the types it saw, guarded by a cheap check; if the check starts failing, it falls back and re-specialises. "Python 3.11 is between 10-60% faster than Python 3.10", 1.25x on average (What's new in 3.11, vendor figure), largely from this. dis.dis(f, adaptive=True) shows the live, rewritten instructions.

Fig. 3 runs one function, total(xs), which sums a list with s = s + x: its frame, its value stack and the six real instructions of its loop (from code/i1_dis.py on Python 3.14.8; stack effects as dis.stack_effect reports them, code/stack_effects.py, run on Python 3.12, the version available on the machine that drew this figure; the fused 3.14 instruction LOAD_FAST_BORROW_LOAD_FAST_BORROW is described from its argument, not measured).

  1. One frame, one value stack. Calling total(xs) makes a frame: the local variables xs, s and x in fixed slots, and a value stack that instructions push to and pop from. GET_ITER has already replaced the list on the stack with an iterator. The figure is the fourth pass of the warm-up call total(list(range(1000))), so s is 0 + 1 + 2 = 3.
  2. FOR_ITER, then STORE_FAST x. FOR_ITER pushes the iterator's next item, 3 (stack effect +1, the iterator stays below it); STORE_FAST pops it into the slot x (-1).
  3. LOAD_FAST_BORROW_LOAD_FAST_BORROW (s, x). One instruction, whose argument names both locals, pushes s and x: 3 and 3.
  4. BINARY_OP (+). Pops two values and pushes their sum, 6 (-1). This generic instruction must find out at run time what + means for these two objects; a sum above 256 would also be a new int object (section 2's small-int cache).
  5. STORE_FAST s, JUMP_BACKWARD. Pops 6 into s, and the back-edge returns to FOR_ITER. Six instructions per element, each one trip round the C evaluation loop: the per-element cost of Fig. 1.
  6. Specialised after 1,000 ints. After the warm-up call the instructions were rewritten in place: BINARY_OP_ADD_INT adds two ints directly after a cheap type check; FOR_ITER_LIST walks a list without the general iterator protocol; JUMP_BACKWARD_NO_JIT is the specialised back-edge (the JIT is off). Outside the loop, RESUME became RESUME_CHECK.
  7. Floats arrive: re-specialised. After 100 calls on lists of 0.5, the int guard failed, the instruction fell back and was specialised again: BINARY_OP_ADD_FLOAT. Code whose types keep changing pays for this churn; code with stable types stays on the fast path.

The three listings the figure is drawn from, side by side (highlighted cells changed since the previous listing; the marked rows are the loop):

linebefore runningafter 1,000 intsafter floats arriveargument
3RESUMERESUME_CHECKRESUME_CHECK0
4LOAD_SMALL_INTLOAD_SMALL_INTLOAD_SMALL_INT0
STORE_FASTSTORE_FASTSTORE_FAST1 (s)
5LOAD_FAST_BORROWLOAD_FAST_BORROWLOAD_FAST_BORROW0 (xs)
GET_ITERGET_ITERGET_ITER
L1:FOR_ITERFOR_ITER_LISTFOR_ITER_LIST11 (to L2)
STORE_FASTSTORE_FASTSTORE_FAST2 (x)
6LOAD_FAST_BORROW_LOAD_FAST_BORROWLOAD_FAST_BORROW_LOAD_FAST_BORROWLOAD_FAST_BORROW_LOAD_FAST_BORROW18 (s, x)
BINARY_OPBINARY_OP_ADD_INTBINARY_OP_ADD_FLOAT0 (+)
STORE_FASTSTORE_FASTSTORE_FAST1 (s)
JUMP_BACKWARDJUMP_BACKWARD_NO_JITJUMP_BACKWARD_NO_JIT13 (to L1)
5L2:END_FOREND_FOREND_FOR
POP_ITERPOP_ITERPOP_ITER
7LOAD_FAST_BORROWLOAD_FAST_BORROWLOAD_FAST_BORROW1 (s)
RETURN_VALUERETURN_VALUERETURN_VALUE

Real output of code/i1_dis.py, dis.dis(total, adaptive=True) on Python 3.14.8; the argument column is the same in all three.

The script behind the listings (i1_dis.py)
i1_dis.py
import dis

def total(xs):
    s = 0
    for x in xs:
        s = s + x
    return s

print("--- before running (generic instructions)")
dis.dis(total, adaptive=True)
total(list(range(1000)))            # warm up with ints only
print("--- after 1000 int additions (specialised in place)")
dis.dis(total, adaptive=True)
for _ in range(100):
    total([0.5] * 1000)             # now feed floats
print("--- after floats arrive (re-specialised)")
dis.dis(total, adaptive=True)

JUMP_BACKWARD_NO_JIT is the loop's back-edge on a build where the experimental JIT is off, which is the default in 3.14 (What's new in 3.14); section 5 turns it on and measures it. The lesson for speed: hot loops whose types never change are the ones CPython can specialise, and even specialised, each element still costs several instructions.

2. What objects cost

Every value is a heap object with a header: a reference count and a pointer to its type, 16 bytes on a 64-bit build. Fig. 4 draws objects to scale, one byte to one unit of length, from sys.getsizeof on Python 3.14.8 (the full output is in the closed block below).

  1. A C int64: 8 bytes. In C, and in a NumPy int64 array, a number is only its value.
  2. A float: 24 bytes. The 16-byte header, the reference count and a pointer to the type object float (one object that every float points at), then the 8-byte double.
  3. An int: 28 bytes. After the header, a size field and the digits, 30 bits in each 4-byte digit, because ints are arbitrary precision. 0 and 1 both take 28 bytes: a Python int is 28 bytes where a C int64 is 8.
  4. 4 more bytes per 30 bits. 2**30 needs a second digit (32 bytes), 2**60 a third (36), 2**100 a fourth (40).

A str stores 1, 2 or 4 bytes per character for the whole string, chosen by its widest character (PEP 393); a non-ASCII string also carries a larger header, which is why 'é' (1 byte per character) costs 61 bytes against 42 for 'a', and '🙂' (4 bytes per character) 64. A list over-allocates: appends reserve spare room in steps (56, 88, 120, 184 bytes as it grows), which is why append is O(1) on average.

Every size measured (i3_sizes.py and its output)
i3_sizes.py
import sys
for v in [0, 1, 2**30, 2**60, 2**100, 1.5, "", "a", "é", "日", "🙂", b"", (), [], {}, set()]:
    print(f"{v!r:>40}  {type(v).__name__:6} {sys.getsizeof(v):4} bytes")
xs, last = [], None
growth = []
for i in range(33):
    size = sys.getsizeof(xs)
    if size != last:
        growth.append((len(xs), size))
        last = size
    xs.append(i)
print("list size jumps (length, bytes):", growth)
real output, Python 3.14.8
                                       0  int      28 bytes
                                       1  int      28 bytes
                              1073741824  int      32 bytes
                     1152921504606846976  int      36 bytes
         1267650600228229401496703205376  int      40 bytes
                                     1.5  float    24 bytes
                                      ''  str      41 bytes
                                     'a'  str      42 bytes
                                     'é'  str      61 bytes
                                     '日'  str      60 bytes
                                     '🙂'  str      64 bytes
                                     b''  bytes    33 bytes
                                      ()  tuple    48 bytes
                                      []  list     56 bytes
                                      {}  dict     64 bytes
                                   set()  set     216 bytes
list size jumps (length, bytes): [(0, 56), (1, 88), (5, 120), (9, 184), (17, 248), (25, 312)]

Reference counting and the cycle collector

When an object's count reaches zero it is freed at once, deterministically; that is why a file closed by going out of scope closes immediately in CPython. Counting cannot free a cycle (A points at B, B at A: both counts stay at 1 after your last name is gone), so a separate cycle collector (gc) periodically looks for groups of objects reachable only from each other. Predict when each object below is freed, then Fig. 5 replays the run:

i2_refcount.py
import gc, sys, weakref

class Node:
    def __init__(self, name):
        self.name, self.other = name, None

a = Node("a")
print("refcount:", sys.getrefcount(a))          # +1 for getrefcount's own argument
b = a
print("refcount:", sys.getrefcount(a))
weakref.finalize(a, print, "  a freed")          # prints when the object dies
del a
print("del a: still alive through b")
del b                                            # count hits 0: freed immediately
print("del b done")

x, y = Node("x"), Node("y")
x.other, y.other = y, x                          # a reference cycle
weakref.finalize(x, print, "  x freed")
weakref.finalize(y, print, "  y freed")
del x, y                                         # counts never reach 0
print("after del x, y: nothing freed yet")
print("gc.collect() found", gc.collect(), "unreachable objects")
print("thresholds:", gc.get_threshold())
Predict the output, then reveal
real output, Python 3.14.8
refcount: 2
refcount: 3
del a: still alive through b
  a freed
del b done
after del x, y: nothing freed yet
  x freed
  y freed
gc.collect() found 4 unreachable objects
thresholds: (2000, 10, 10)

Fig. 5 follows i2_refcount.py line by line; each step quotes what the run printed (Python 3.14.8). The stacked discs on an object are its reference count.

  1. a = Node("a"): one reference. The name a refers to the new object, so its count is 1. sys.getrefcount reports one more than you expect because its own argument is a reference: it printed "refcount: 2".
  2. b = a: two. A second name for the same object: "refcount: 3".
  3. del a: one. Deleting a name removes a reference, not the object: "del a: still alive through b".
  4. del b: zero, freed at once. a died the instant its last name went: its finaliser printed "a freed" before the next line, "del b done".
  5. A cycle. x.other, y.other = y, x: each object now has two references, its name and the other's .other.
  6. del x, y: both counts stay at 1. The names are gone, but each object still holds the other, so neither count reaches zero: "after del x, y: nothing freed yet".
  7. gc.collect() frees the cycle. The collector found the pair reachable only from each other and freed both ("x freed", "y freed"): the cycle survived del until gc.collect(), which reported "found 4 unreachable objects".

The thresholds (2000, 10, 10) are those of the generational collector: Python 3.14.0 to 3.14.4 shipped an incremental collector, and 3.14.5 reverted to "the generational GC from 3.13" after "reports of significant memory pressure in production environments" (What's new in 3.14, Garbage collection).

Practical consequences: break cycles in long-lived structures (parent pointers, callbacks that capture self) or use weakref; do not rely on __del__ for clean-up (use with); and for PyTorch, a tensor held by a cycle keeps its GPU memory until the collector runs. What both mechanisms do to a process's memory (pymalloc's arenas and pools, freed memory that does not go back to the operating system, the copy-on-write cost in DataLoader workers) is Memory allocators, section 7.

Two implementation details that leak into results

Integer caching
a = 1000
b = 999 + int('1')
print(a == b, a is b, 10 is 5 + 5)
Predict the output, then reveal
real output, Python 3.14.8 (outputs/q_drills.json)
<drill>:3: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
True False True

CPython keeps one shared object for every integer from -5 to 256 ("The current implementation keeps an array of integer objects for all integers between -5 and 256", C API, integer objects), so 10 is 5 + 5 is True while two separately made 1000s are different objects; the compiler warns about is with a literal. Compare values with ==; is is for None and sentinels.

Float arithmetic
print(0.1 + 0.2 == 0.3, round(2.5), round(3.5), 7 // -2, -7 % 3)
Predict the output, then reveal
real output, Python 3.14.8 (outputs/q_drills.json)
False 2 4 -4 2

A float is an IEEE 754 double, so 0.1 and 0.2 are not exact; round rounds halves to even; // and % round towards minus infinity. Why, and what it does to training numerics, is Numerical computing.

On the same accounting, the built-in containers have the costs below: fast where the work stays inside one C structure, slow where every element must be visited or a new object made.

What the built-in containers cost (type, what it is, fast and slow operations)
TypeIsFastSlow
listDynamic array of pointersindex, append (amortised O(1)), pop from the endx in list, insert or pop at the front (O(n))
collections.dequeLinked blocksappend and pop at both endsindexing the middle
dict, setHash tables (dict keeps insertion order)lookup, insert, delete: O(1) on averagememory (about 2x a plain object per record; Python: the data model and protocols measures it)
tupleImmutable arraycreation, hashing (if items hash)any "change" makes a new tuple
str, bytesImmutable; str is Unicode code points, bytes raw octets; convert with encode/decode at the edgesslicing, in, joins += t in a loop (a new string each time; use "".join)
int, floatArbitrary-precision integer; IEEE 754 doublesmall valuesevery operation allocates a new object (above)

Time complexities as listed on the Python wiki's TimeComplexity page.

3. Measure first: profiling

The order that works: measure where the time goes, fix the algorithm or data structure, push loops into code that runs in C (built-ins, re, NumPy), and only then write native code. Guessing skips the first step and usually optimises the wrong thing.

The subject is a deliberately slow version of the root page's token counter: it calls a Python function for every character and keeps per-user totals in two parallel lists (p1_slow.py, in the closed block below). cProfile (standard library) records every function call. Before reading its report:

python p1_profile.py: cProfile on per_user(), then both versions timed without it (real output, Python 3.14.8)
         8194880 function calls in 1.456 seconds

   Ordered by: internal time
   List reduced from 18 to 6 due to restriction <6>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  2669805    0.631    0.000    1.016    0.000 p1_slow.py:11(is_token_char)
    20000    0.323    0.000    1.340    0.000 p1_slow.py:14(count_tokens)
  2614667    0.203    0.000    0.203    0.000 {method 'isalnum' of 'str' objects}
  2669805    0.183    0.000    0.183    0.000 {method 'isascii' of 'str' objects}
        1    0.033    0.033    1.456    1.456 p1_slow.py:23(per_user)
    20000    0.023    0.000    0.023    0.000 {method 'index' of 'list' objects}


p1_slow: 206 ms per run (no profiler)
p1_fast: 74 ms per run (no profiler)

Read tottime (time inside the function itself) first: 2.7 million calls of is_token_char, one per character, dominate. The list scans that look bad on paper (users.index) cost 23 ms, because there are only 200 users. The fix follows the profile: count with a compiled regular expression (the loop over characters then runs inside the C regex engine) and keep totals in a dict (a Counter). Same answer (the script asserts it), 206 ms down to 74 ms.

The slow and the fast version (p1_slow.py, p1_fast.py)
p1_slow.py
def count_tokens(text):
    n, inside = 0, False
    for c in text:                          # one Python-level call per character
        tok = is_token_char(c)
        if tok and not inside:
            n += 1
        inside = tok
    return n

def per_user(lines):
    users, totals = [], []                  # parallel lists: `in` and .index() scan them
    for line in lines:
        msg = json.loads(line)
        u = msg["user"]
        if u not in users:
            users.append(u)
            totals.append(0)
        totals[users.index(u)] += count_tokens(msg["text"])
    return sorted(zip(users, totals), key=lambda p: (-p[1], p[0]))[:5]
p1_fast.py
"""The same result after reading the profile: a dict instead of list scans, and a compiled regex
instead of a Python-level loop over characters."""
import json, re
from collections import Counter
from p1_slow import make_log

TOKEN = re.compile(r"[A-Za-z0-9]+")         # the same token rule, run by the C regex engine

def per_user(lines):
    totals = Counter()
    for line in lines:
        msg = json.loads(line)
        totals[msg["user"]] += len(TOKEN.findall(msg["text"]))
    return sorted(totals.items(), key=lambda p: (-p[1], p[0]))[:5]

A deterministic profiler like cProfile adds work to each of 8 million calls, so it distorts call-heavy code: trust its ranking, not its absolute times. A sampling profiler looks at the stack a few hundred times a second and barely slows the program. Two of them:

  • py-spy: "a sampling profiler for Python programs ... without restarting the program or modifying the code in any way" (py-spy); attach to a running server with py-spy top --pid or py-spy dump. On macOS "OSX always requires running as root", which is what happened here (below). Using it on a live service, with flame graphs and off-CPU time, is Capacity planning and performance.
  • Scalene samples per line and splits time into Python and native code (and memory, if asked). Its summary for the whole slow script, which also builds the 20,000-line test log, attributes about half the run (49%) to make_log, the fake-data generator that cProfile was not asked to measure: profile the whole program, not just the function you suspect.

Fig. 6 · cProfile made the program 7 times slower; the fix it pointed to made it 2.8 times faster

The py-spy refusal and the Scalene summary (real outputs)
py-spy record -- python p1_slow.py (real output, py-spy 0.4.2, macOS 27, no sudo)
This program requires root on OSX.
Try running again with elevated permissions by going 'sudo !!'
scalene run --cpu-only p1_slow.py, then scalene view --cli -r (real output, Scalene 2.3.0)
Function summaries:
  make_log (line 4): 4% Python, 45% native
  is_token_char (line 11): 9% Python, 11% native
  count_tokens (line 14): 6% Python, 2% native
  per_user (line 23): 0% Python, 12% native

Scalene's Python/native split is sampled and approximate; treat it as a pointer, not a measurement.

4. Move the loop out of Python

NumPy stores numbers in one contiguous typed buffer and runs each operation as a C loop over it, with no per-element object, method lookup or reference count. The hero's reduction (the denominator of a softmax, sum(exp(x - max(x)))) as a Python loop, as map with math.fsum, and as NumPy, from 10 to a million elements:

The script and its output (p2_numpy.py)
p2_numpy.py
"""Softmax-style work (sum of exp(x - max)) on n floats: a Python loop, a generator with
math.exp, and NumPy, plus the cost of converting the list to an array. Median of timeit repeats, in microseconds per call."""
import math, os, statistics, sys, timeit
import numpy as np

def py_loop(xs):
    m = max(xs)
    s = 0.0
    for x in xs:
        s += math.exp(x - m)
    return s

def py_builtin(xs):
    m = max(xs)
    return math.fsum(map(math.exp, (x - m for x in xs)))

def np_vec(a):
    return np.exp(a - a.max()).sum()       # three passes in C over a contiguous buffer

def us(f, arg):
    t = timeit.Timer(lambda: f(arg))
    n, _ = t.autorange()
    return statistics.median(t.repeat(5, n)) / n * 1e6

print(f"Python {sys.version.split()[0]}, NumPy {np.__version__}, load {os.getloadavg()[0]:.2f}")
print(f"{'n':>9} {'loop':>11} {'map+fsum':>11} {'numpy':>11} {'np.array(list)':>15}  numpy speed-up over loop")
for n in (10, 1_000, 100_000, 1_000_000):
    xs = [((i * 7919) % 1000) / 100 for i in range(n)]
    a = np.array(xs)
    assert abs(py_loop(xs) - np_vec(a)) < 1e-6 * py_loop(xs)
    t1, t2, t3, t4 = us(py_loop, xs), us(py_builtin, xs), us(np_vec, a), us(np.array, xs)
    print(f"{n:>9,} {t1:>9.1f}us {t2:>9.1f}us {t3:>9.1f}us {t4:>13.1f}us  {t1 / t3:6.1f}x")
real output, Python 3.14.8
Python 3.14.8, NumPy 2.5.3, load 6.27
        n        loop    map+fsum       numpy  np.array(list)  numpy speed-up over loop
       10       0.6us       0.8us       1.4us           0.4us     0.4x
    1,000      47.5us      53.7us       4.6us          20.4us    10.3x
  100,000    4777.5us    5466.8us     308.3us        2071.0us    15.5x
1,000,000   47592.6us   53931.6us    3195.0us       20325.1us    14.9x

Three lessons, all from the measurement. At 10 elements NumPy is slower than the loop (a fixed cost of about a microsecond per NumPy call). From a thousand elements up it is 10 to 16 times faster. And converting a Python list to an array costs about 40% of the whole Python loop: keep data in arrays from the start (load with NumPy, pandas, polars or PyTorch), or the conversion eats the gain. Clever pure Python (map, fsum) did not help: the per-element work is still Python objects.

Fig. 7 · NumPy loses at 10 elements and wins 10 to 16 times from a thousand up

When to drop to native code

When the profile shows a hot loop that is not array arithmetic (a tokenizer, a parser, a graph walk, a custom sampler), no library already does it, and it is called often enough to matter. Then write that one function in a compiled language and call it from Python. Rust: speeding up Python with PyO3 and maturin does exactly this, from one function to a published wheel, and compares the alternatives (Cython, Numba, mypyc, nanobind or pybind11 for C++, cffi); C++: the machine underneath shows what the CPU does underneath. The root's Benchmark tab measures the token counter in all four languages and the cost of each crossing between Python and native code: batch work so you cross once per array, not once per element.

Cheap wins first

A dict or set instead of list membership; str.join instead of += in a loop; built-ins (sum, sorted, re, collections.Counter) over hand loops; local variables in hot loops; caching (Python: the data model and protocols).

Then

NumPy or PyTorch for numbers; processes or the free-threaded build for parallel CPU work, asyncio for waiting (Python: concurrency, asyncio and the GIL); a Rust or C++ extension for the hot loop that is left.

Mistakes

Optimising without a profile; timing once (use timeit or hyperfine, take the median); trusting cProfile's absolute times; micro-benchmarking with a warm cache and deploying with a cold one.

5. The experimental JIT, on and off

A JIT (just-in-time compiler) turns hot code into machine code while the program runs. CPython's (PEP 744, since 3.13) is a copy-and-patch JIT: when the specialising interpreter of section 1 finds a hot loop, it records a trace of its micro-operations and stitches together machine-code templates ("stencils") that were compiled with LLVM when CPython itself was built, so you need no LLVM at run time. It ships compiled into the official macOS and Windows installers and the uv builds used here, but is off unless you set PYTHON_JIT=1; in 3.14 and later, sys._jit.is_enabled() tells you whether it is on.

Read Fig. 8 as: on 3.15 the JIT sped up the plain Python loops (character scanning 1.64x, float arithmetic) by about half or more, helped small-object code less, and did not help (here, slightly slowed) the generator pipeline, inside What's New's own range for 3.15 ("roughly 15% slowdown to over 100% speedup", 11-12% geometric mean on AArch64 macOS; What's new in 3.15, vendor figure). The 3.13 JIT gave the character loop about the same (1.66x); the 3.14 JIT on this machine is mostly a wash, sometimes slower. Trust the direction, not the digits: the final run was made with a load average around 10, and an earlier run the same day (src/pb/out/jit_earlier_run.txt) gave 1.5x instead of 2.4x for json_count on 3.15.

It is off by default in 3.15 too, and a 2x speed-up of a Python loop is still far from moving the loop to NumPy or Rust (section 4; the root's Benchmark tab measures the token counter in all four languages).

Fig. 8 · The 3.15 JIT speeds up plain loops, not generator pipelines; the 3.14 JIT is mostly a wash

Method and every time measured (the language page's Runtime lab, part 3)

Five workloads (src/pb/jit/jit_cases.py): each is timed 7 times after 3 warm-ups inside one process (median), and that process is run 3 times per setting (median of the three). PYTHON_JIT=0 and =1 on the uv builds of 3.13.16, 3.14.8 and 3.15.0rc3, all configured with --enable-experimental-jit=yes-off (built in, off by default). "JIT on" is confirmed by sys._jit.is_enabled() on 3.14 and 3.15 (3.13 has no such function).

The mistake this avoids: measuring the JIT with one run on a busy laptop. The differences here are tens of percent; noise on a loaded machine is several percent. Run each case in several fresh processes, take medians, and record the load, as this page does.

The old page's JIT claims, checked

Old page "Python: staying current": 3.13 "copy-and-patch JIT ... modest gains"; 3.14 JIT "wins on tight loops". imprecise Measured above: gains depend on the workload and the version. The 3.13 and 3.15 JITs sped up the character loop by about 1.6x; the 3.14 JIT was mostly a wash; the 3.15 JIT is the broadest win on tight loops.

6. What changed from 3.12 to 3.15, and what it means for your code

A new CPython ships every October (PEP 602) and gets two years of bug fixes, then security fixes until five years. 3.15.0 was released on 2026-10-09 and is the newest feature line; 3.14 (3.14.8) is in bug fixes, 3.12 and 3.13 get security fixes only (PEP 790; devguide). The measurements on this page used 3.15.0rc3 (2026-10-02), the last release candidate before the final.

Fig. 9 draws each line from its first release to its end of life: what a project that supports "every Python still getting fixes" must test in October 2026 is 3.11 to 3.15 (3.11 reaches end of life in 2027-10).

Fig. 9 · Each line gets bug fixes for two years, then security fixes to five

ReleaseLanguage and libraryRuntimeWhat it changes for you
3.12
2023-10-02, security fixes to 2028-10
def f[T] and type X = ... (PEP 695); f-strings in the grammar (PEP 701); typing.override (PEP 698); itertools.batched; Path.walk; the buffer protocol from Python (PEP 688); better "did you forget to import" errorsA per-interpreter GIL in the C API (PEP 684), the groundwork for 3.14's subinterpreters; comprehensions inlined (PEP 709)The oldest version worth targeting for new code: it is where modern generic syntax starts
3.13
2024-10-07, security fixes to 2029-10
Type parameter defaults (PEP 696), TypeIs (PEP 742), ReadOnly TypedDict items (PEP 705), warnings.deprecated (PEP 702), copy.replace; 19 "dead batteries" and lib2to3 removed (PEP 594); defined locals() semantics (PEP 667)New interactive REPL (colour, multi-line editing; based on PyPy's); experimental free-threaded build (PEP 703); experimental JIT, off by default (PEP 744)Old scripts that import cgi or telnetlib break
3.14
2025-10-07, bug fixes; 3.14.8 on 2026-09-30
t-strings (PEP 750); deferred annotations (PEP 649/749); except A, B without parentheses (PEP 758); compression.zstd (PEP 784); concurrent.interpreters (PEP 734); a SyntaxWarning for return in finally (PEP 765)Free-threaded build officially supported (PEP 779); JIT in the official macOS and Windows installers, still off by default; python -m asyncio ps PID and pstree show a running program's tasks; safe external debugger attach (PEP 768)Forward references need no quotes; try free-threading for CPU-bound threads
3.15
2026-10-09 (rc3 2026-10-02)
lazy import (PEP 810); frozendict (PEP 814) and sentinel (PEP 661) built-ins; [*xs for xs in ...] (PEP 798); UTF-8 by default (PEP 686); profiling package with the Tachyon sampler (PEP 799); TypedDict extra items (PEP 728), TypeForm (PEP 747)The JIT "significantly upgraded" (What's New: 11-12% faster than the tail-calling interpreter on AArch64 macOS, pyperformance geometric mean) but still off by default; frame pointers on by default (PEP 831); a stable ABI for free-threaded builds, abi3t (PEP 803)Pass encoding= explicitly; use lazy import in CLIs; ship abi3t wheels if you build extensions

The runtime column is taught where it matters: free-threading and subinterpreters on Python: concurrency, asyncio and the GIL, the typing PEPs and abi3t wheels on Python: typing, uv, packaging and the toolchain, the JIT in section 5 and lazy imports in section 7. The Version explorer tab runs 21 small programs, one per change, on 3.11 to 3.15 and shows the real output of each; pick your minimum version there to see which features you can use.

The quiet one: UTF-8 by default

Before 3.15, open() without encoding= used the locale's encoding, so the same script read a file differently on a Windows machine or a server with a Latin-1 locale. The same two-line snippet, run under an en_US.ISO8859-1 locale (the plain C locale already turns UTF-8 mode on):

So move to 3.15 deliberately: lazy import for CLIs, and pass encoding= wherever you open text files, because on 3.15 the default is UTF-8 on every platform while older versions in your support range still use the locale.

Corrections to the old page "Python: staying current"
  • "Python 3.15 is due 2026-10-01": a third release candidate was added (2026-10-02) and the final shipped on 2026-10-09 (PEP 790).
  • "Python 3.15 ... lazy imports and abi3t are its headline items": true but incomplete; What's New also lists frozendict, sentinel, UTF-8 as the default encoding, unpacking in comprehensions, the Tachyon profiler and the JIT upgrade as highlights.
  • "abi3t lets NumPy-class extensions ship one wheel per platform": imprecise. One cp315-abi3.abi3t wheel covers 3.15 and later on both builds, but free-threaded 3.14 still needs its own wheel, and of 25 popular compiled packages only one (cryptography) ships an abi3t wheel today (the wheel survey is on Python: typing, uv, packaging and the toolchain).
  • "from __future__ import annotations is finally obsolete": imprecise. It still works and is deprecated; What's New 3.14 says removal will not happen before 3.13's end of life in 2029.
  • "t-strings ... showing up in LLM prompt-templating libraries": no source given; not confirmed here, so left out.

Fig. 10 · Three unused imports cost three quarters of the start-up

7. Lazy imports (3.15), measured

A Python program's start-up time is mostly imports: each import finds a file, loads or compiles its bytecode and runs all its top-level code, including its own imports. A command-line tool that imports httpx, pydantic and rich at the top pays for all three even when the user only asked for --help. Until now the fix was to move imports inside functions. 3.15 adds lazy import (PEP 810): the name is bound to a lightweight proxy and the module loads the first time the name is used.

import argparse lazy import httpx # was: import httpx lazy import pydantic # was: import pydantic lazy from rich.console import Console # was: from rich.console import Console

That is the only change between the two files measured below (src/pb/lazy/). Both run the fast path, count "hello world", which needs none of the three libraries. Fig. 10 steps through what Python imports, to scale, in five or six stretches; switching mode starts again from the first import:

  1. Start-up machinery: 2.8 ms, 12 modules. _frozen_importlib_external, zipimport, encodings, encodings.utf_8 and _signal: what every Python process imports before your first line, the same in all three runs.
  2. site: 6.8 ms, 26 modules. site sets up sys.path and the environment's site-packages; also the same in every run.
  3. argparse: 4.3 ms, 10 modules. Your first line of code: import argparse, eager in all versions of the file.
  4. httpx: 46.6 ms, 153 modules. The HTTP client and everything it imports at start-up (among them http.client, ssl, socket, email, idna, zstandard), loaded although count never uses it.
  5. pydantic and rich.console: 63.4 ms, 67 modules. pydantic 16.0 ms, rich.console 47.4 ms, both loaded although unused. Three unused imports cost most of the start-up.
  6. Done: 123.9 ms of import time, 268 modules. The program printed 2. Measured without -X importtime, the whole run took 100 ms (median of 30).

What to take from it: the lazy file loads 64 of the eager file's 268 modules and the whole run takes 26 ms instead of 100 ms (hyperfine medians), and the global switch -X lazy_imports=all (or PYTHON_LAZY_IMPORTS=all) gets the same result without editing the file. The work has not disappeared: a run that uses httpx pays for it at the first use instead.

What it costs, and when not to use it
  • Errors move: a misspelled module raises at first use, not at start-up; the traceback shows both places.
  • Import side effects (a plugin registering itself, logging configured at import) happen later or never. Do not make such imports lazy; the global all mode can be filtered with sys.set_lazy_imports_filter.
  • Only at module level: lazy inside a function, a class body or a try block is a SyntaxError, and so is lazy from x import *.
  • Code that must also run on 3.14 or older cannot use the keyword (it is a SyntaxError there; see the Version explorer); list the modules in __lazy_modules__ instead, which older versions ignore.
The PEP and the release disagree on one detail
PEP 810 (status Final) describes three global modes, normal, all and none (none would force every import eager, for debugging). 3.15.0rc3 accepts only two, as What's New says:
Use normal to undo all; there is no switch that forces explicit lazy imports eager.

Fig. 11 · The whole run: 100 ms eager, 26 ms lazy

Built 2026-10-26 by splitting the Python language page (its Part 1 sections 11 and 12 and the containers table of section 13, Part 2 sections 7, 8 and 10, the Version explorer tab and Runtime lab part 3); every output is the recorded run from that page, made on 2026-10-05 on an Apple M1 Pro in normal use (src/README.md says how). What transfers to a Linux server: which approach wins and the shape of each result; what does not: absolute times.