Skip to content

Instantly share code, notes, and snippets.

@maludwig
Created January 10, 2023 20:39
Show Gist options
  • Save maludwig/d38054ec05d01ad91df5dade8aa47d9d to your computer and use it in GitHub Desktop.
Save maludwig/d38054ec05d01ad91df5dade8aa47d9d to your computer and use it in GitHub Desktop.
What is the fastest way to get the first key in a dictionary?
from time import perf_counter_ns
NANOS_PER_SECOND = 1_000_000_000
ITER_COUNT = 100_000
biased_dict = {"one_key_to_rule_them_all": 42}
def first_1():
return next(iter(biased_dict))
def first_2():
return list(biased_dict)[0]
def first_3():
return next(iter(biased_dict.keys()))
def first_4():
return list(biased_dict.keys())[0]
def first_5():
for key in biased_dict:
return key
def first_6():
for key in biased_dict.keys():
return key
def first_7():
for key, v in biased_dict.items():
return key
def benchmark(fn):
start_ns = perf_counter_ns()
for _ in range(ITER_COUNT):
fn()
end_ns = perf_counter_ns()
duration_ns = end_ns - start_ns
return {
"duration_ns": duration_ns,
"ns_per_iteration": duration_ns / ITER_COUNT,
"iterations_per_sec": int(NANOS_PER_SECOND // (duration_ns / ITER_COUNT)),
}
def main():
results = {}
for fn_name, fn in [
("first_1", first_1),
("first_2", first_2),
("first_3", first_3),
("first_4", first_4),
("first_5", first_5),
("first_6", first_6),
("first_7", first_7),
]:
benchmark(fn)
results[fn_name] = benchmark(fn)
sorted_results = sorted(results.items(), key=lambda item: item[1]["duration_ns"])
print("Results are printed with the fastest function at the top, and the slowest at the bottom")
fastest_fn_name, fastest_result = sorted_results[0]
slowest_fn_name, slowest_result = sorted_results[-1]
for fn_name, result in sorted_results:
if fn_name == fastest_fn_name:
print(fn_name + " (Fastest!):")
else:
x_slower_than_fastest = result["duration_ns"] / fastest_result["duration_ns"]
print(f"{fn_name} ({x_slower_than_fastest:.2}x slower than {fastest_fn_name}):")
print(f" duration: {result['duration_ns']}ns")
print(f" ns_per_iteration: {result['ns_per_iteration']}ns")
print(f" iterations_per_sec: {result['iterations_per_sec']} per second")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment