Skip to content

Instantly share code, notes, and snippets.

@hofrob
Last active April 1, 2024 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hofrob/ad143aaa84c096f42489c2520a3875f9 to your computer and use it in GitHub Desktop.
Save hofrob/ad143aaa84c096f42489c2520a3875f9 to your computer and use it in GitHub Desktop.
Compare timings of dict constructor with literal dict
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")
@hofrob
Copy link
Author

hofrob commented Oct 31, 2022

Result

Construct n=500000 dicts with these random values: values=['zlh3wqFTEA', '0QE2KPvpfc', 'uBGj31IYCG', 'tkgopdTVkF', 'H3AZwyrqKo', 'Mcg78nqIss', 'KKhhOKjfII', 'rBpQ6WsJhm', 'vMVEdBeIZz', '2CUR1yfWEQ']
---
   dict constructor: 255.3ms
       literal dict: 207.7ms
---
A literal dict is 18.65% faster

@PhilMarsh
Copy link

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
Construction Time (ms) per Container Size
% Literal Speedup per Container size
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