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 None10.1 ns if x is None: passWhen x = True:13.9 ns x is None11.1 ns if x is None: passHow 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 repeatimport sysfor 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)