Last active
September 24, 2024 10:21
-
-
Save hofrob/ad143aaa84c096f42489c2520a3875f9 to your computer and use it in GitHub Desktop.
Compare timings of dict constructor with literal dict
This file contains 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
import random | |
import string | |
import time | |
values = [] | |
for i in range(10): | |
values.append("".join(random.choices(string.ascii_letters + string.digits, k=10))) | |
n = 500000 | |
print(f"Construct {n=} dicts with these random values: {values=}") | |
print("---") | |
begin_dict = time.time_ns() | |
for i in range(n): | |
dict( | |
a0=values[0], | |
a1=values[1], | |
a2=values[2], | |
a3=values[3], | |
a4=values[4], | |
a5=values[5], | |
a6=values[6], | |
a7=values[7], | |
a8=values[8], | |
a9=values[9], | |
) | |
constructor_timing = time.time_ns() - begin_dict | |
print(f"{'dict constructor:':>20} {constructor_timing / 10 ** 6:.1f}ms") | |
begin_dict = time.time_ns() | |
for i in range(n): | |
{ | |
"a0": values[0], | |
"a1": values[1], | |
"a2": values[2], | |
"a3": values[3], | |
"a4": values[4], | |
"a5": values[5], | |
"a6": values[6], | |
"a7": values[7], | |
"a8": values[8], | |
"a9": values[9], | |
} | |
literal_timing = time.time_ns() - begin_dict | |
print(f"{'literal dict:':>20} {literal_timing / 10 ** 6:.1f}ms") | |
percentage_difference = (constructor_timing - literal_timing) / constructor_timing * 100 | |
print("---") | |
print(f"A literal dict is {percentage_difference:.2f}% faster") |
I was curious how the number of keys might effect the time difference.
I re-ran this script with 0, 1, 2, 5, 10, 20, and 50 values using Python 3.9.16 on a Mac Pro M2: https://gist.github.com/PhilMarsh/1c7c695631cd0cd1a3924371fe3764c9
1 The "% speedup" graph has a logarithmic trend line here, but power series also fit pretty well (maybe better?).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result