Skip to content

Instantly share code, notes, and snippets.

@markis
Last active October 12, 2022 22:41
Show Gist options
  • Save markis/420bbc610decdd16d933f24c205aec6d to your computer and use it in GitHub Desktop.
Save markis/420bbc610decdd16d933f24c205aec6d to your computer and use it in GitHub Desktop.
from collections import defaultdict
import numpy
from timeit import timeit
DATA = {"value": 1}
def square_bracket():
assert DATA["value"] is not None
def square_bracket_not_exists():
value = "non_existent" in DATA and DATA["non_existent"] or None
assert value is None
def get_method():
assert DATA.get("value") is not None
def get_method_not_exists():
assert DATA.get("non_existent") is None
def get_method_not_exists_with_default():
assert DATA.get("non_existent", None) is None
def square_bracket_not_exists_try():
try:
assert DATA["non_existent"] is not None
except KeyError:
pass
RUNS = 5000
timing = defaultdict(list)
funcs_to_time = [
square_bracket,
square_bracket_not_exists,
get_method,
get_method_not_exists,
get_method_not_exists_with_default,
square_bracket_not_exists_try,
]
for _ in range(RUNS):
for func in funcs_to_time:
timing[func.__name__].append(timeit(func, number=RUNS))
for key, values in timing.items():
print(
f"{key},{numpy.mean(values)},{numpy.percentile(values, 90)},"
f"{numpy.percentile(values,95)},{numpy.percentile(values,99)}"
)
@markis
Copy link
Author

markis commented Oct 12, 2022

.get is about 18% slower than using the square bracket accessor. These runs were using python 3.10 on an M1 mac.

Screen Shot 2022-10-12 at 3 57 35 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment