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?
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.