28

Why is the Python dict constructor slower than the using literal syntax?

After hot debate with my colleague, I did some comparison and got the following statistics:

python2.7 -m timeit "d = dict(x=1, y=2, z=3)"
1000000 loops, best of 3: 0.47 usec per loop

python2.7 -m timeit "d = {'x': 1, 'y': 2, 'z': 3}"
10000000 loops, best of 3: 0.162 usec per loop

What is the reason the constructor is slower? And in what situations, if any, would it be faster?

Fabz
  • 303
  • 1
  • 3
  • 5
  • 4
    Usually this has to do with the fact that `dict` could point to something else. So the interpreter can't make any real optimizations. With the `{}` syntax, it can make those optimizations. – Bill Lynch Oct 10 '14 at 23:10
  • 7
    that is: `dict` is always a genuine function call, whereas `{}` is handled at compile time. – Eevee Oct 10 '14 at 23:11
  • 3
    possible duplicate of [differences between "d = dict()" and "d = {}"](http://stackoverflow.com/questions/2745008/differences-between-d-dict-and-d) – Padraic Cunningham Oct 11 '14 at 00:08

1 Answers1

37

The constructor is slower because it creates the object by calling the dict() function, whereas the compiler turns the dict literal into BUILD_MAP bytecode, saving the function call.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358