Last active
October 12, 2022 22:41
-
-
Save markis/420bbc610decdd16d933f24c205aec6d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)}" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
.get
is about 18% slower than using the square bracket accessor. These runs were using python 3.10 on an M1 mac.