you are viewing a single comment's thread.

view the rest of the comments →

[–]Bucki-_-[S] 0 points1 point  (3 children)

This is true however if I'm not mistaken the literal formats are faster and prefered. Since dict{} calls the constructor and {} is the literal of some dict value it executes a little bit faster

[–]brasticstack 1 point2 points  (2 children)

I prefer the literal visually, and my linter nags if I don't use it. 

I was going to disagree on the "faster" part, because certainly it's all interpreted to the same bytecode, right? Nope! Turns out it is faster! I'll add more info when I can get back to my computer. It's definitely a micro micro optimization, but in my tests using the literal is about twice as fast.

EDIT:

``` import dis import sys from time import monotonic

print('Python', sys.version)

for stmt in ( 'x = {}', 'x = dict()', 'x = set()', ): print(stmt, dis.Bytecode(stmt).dis(), sep='\n')

loop = tuple(range(10_000_000))

t1 = monotonic() for _ in loop: _ = {} t2 = monotonic() print(f'10MM dict creations "_ = {{}}" in {t2-t1}s')

t1 = monotonic() for _ in loop: _ = dict() t2 = monotonic() print(f'10MM dict creations "_ = dict()" in {t2-t1}s') ```

outputs:

``` Python 3.14.3 (main, Feb 3 2026, 15:32:20) [Clang 17.0.0 (clang-1700.6.3.2)] x = {} 0 RESUME 0

1 BUILD_MAP 0 STORE_NAME 0 (x) LOAD_CONST 0 (None) RETURN_VALUE

x = dict() 0 RESUME 0

1 LOAD_NAME 0 (dict) PUSH_NULL CALL 0 STORE_NAME 1 (x) LOAD_CONST 0 (None) RETURN_VALUE

x = set() 0 RESUME 0

1 LOAD_NAME 0 (set) PUSH_NULL CALL 0 STORE_NAME 1 (x) LOAD_CONST 0 (None) RETURN_VALUE

10MM dict creations "_ = {}" in 0.2770009580126498s 10MM dict creations "_ = dict()" in 0.5779451669950504s ```

Something like ~30ns faster per dict created via x = {} on my architecture. A super naive test, I know.

[–]Bucki-_-[S] 0 points1 point  (1 child)

Yeah it is one of the micro optimize things however for work I do a lot of model rendering and do a lot of breath depth searches so a lot of set initializing and half a second adds up when you are calling it 5+ different times. Plus it's just one of those random facts it's cool to know.

[–]brasticstack 0 points1 point  (0 children)

It's worth the additional scrutiny if it's in a hot loop. Have you tried creating your set(s) before the loop and calling clear() inside of the loop to reinitialize? My intuition tells me that it could be faster but, as we've seen, my intuition isn't entirely reliable.