Why is typical Python code slower than equivalent C code, beyond "Python is interpreted"?
Answer
Beyond bytecode interpretation overhead, every Python value is a heap-allocated, reference-counted object (even small integers), so simple arithmetic involves pointer chasing and dynamic dispatch instead of raw CPU registers and machine instructions. Dynamic typing means an operation like `a + b` generally needs its implementation resolved based on the runtime types involved, rather than a compiler resolving it once ahead of time — though modern CPython (3.11 onward) uses an internal specializing adaptive interpreter that caches the resolved operation for repeated bytecode sites, so a hot loop doing the same kind of addition repeatedly is meaningfully faster than a naive per-operation lookup model would suggest, without a literal `__add__` method lookup happening on every single pass. This dynamic-object overhead, softened but not eliminated by specialization, is exactly why performance-critical Python code typically delegates the hot inner loop to a C extension (NumPy, Cython, Rust bindings) rather than trying to out-optimize the interpreter in pure Python.
Strong answer includes
- every value is a heap-allocated, reference-counted object, even integers
- dynamic typing means operator resolution generally happens per call, not once at compile time
- CPython 3.11+ specializes hot bytecode sites internally, softening but not eliminating that overhead
Practical example
A pure-Python loop summing a million floats is typically an order of magnitude slower than the equivalent
numpy.sum()call, because NumPy performs the summation in compiled C over a contiguous flat memory buffer.