例外で分岐 is ~4.11× slower than in で判定
Catching a KeyError is slower than checking membership first, at this miss rate.
Result
| Run | 例外で分岐 | in で判定 | Ratio |
|---|---|---|---|
| Run 1 | 47.067 | 11.884 | 3.96× |
| Run 2 | 49.678 | 12.101 | 4.11× |
| Run 3 | 49.949 | 12.139 | 4.11× |
Spread over 3 runs: 例外で分岐 CV 2.6% / in で判定 CV 0.9% / Ratio CV 1.7%
Conditions
200,000 lookups against a dict where the key never exists.
Where this number does not apply
If most lookups hit, the exception path becomes cheap — the crossover depends on the miss rate.
Reproduce
cd bench && python micro_py.py --out ../data/run.json --samples 21