Timing results in Python 3.12 (and similar with 3.11 and 3.13 on different machines):
When x = None:
13.8 ns x is None
10.1 ns if x is None: pass
When x = True:
13.9 ns x is None
11.1 ns if x is None: pass
How can doing more take less time?
Why is if x is None: pass faster, when it does the same x is None check and then additionally checks the truth value of the result (and does or skips the pass)?
Times on other versions/machines:
- Python 3.11: (12.4, 9.3) and (12.0, 8.8)
- Python 3.13: (12.7, 9.9) and (12.7, 9.6)
Benchmark script (Attempt This Online!):
from timeit import repeat
import sys
for x in None, True:
print(f'When {x = }:')
for code in ['x is None', 'if x is None: pass'] * 2:
t = min(repeat(code, f'{x=}', repeat=100))
print(f'{t*1e3:4.1f} ns ', code)
print()
print('Python:', sys.version)
Look at the disassembled code:
The
ifcase has a specialPOP_JUMP_IF_NOT_NONEoperation, which is faster than aLOAD_CONSTplusIS_OP. You can read the detailed discussion about it here: https://github.com/faster-cpython/ideas/discussions/154.