|
|
|
|
|
by klodolph
1719 days ago
|
|
There are some weird performance optimizations in Python, e.g., item = some_dict.get(key)
if item is None:
# key does not exist
Versus try:
item = some_dict[key]
except KeyError:
# key does not exist
When I tested these (admittedly, a while ago), which one was faster depended on how often the key was missing. If “missing key” was an expected case, the first one was faster. If “missing key” was uncommon, the second was faster. It sounds like the fast path in the second case is getting faster, so this performance gap may be increasing. |
|
First approach is looking for `get` in `type(some_dict).__dict__` and then for `key` in `some_dict`. Second approach is looking for `key` in `some_dict`, and then (only if missing) for `KeyError` in the module globals/builtins.
If the performance of hash lookups matters, Python is the wrong language for you.