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?
With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.
Python Language Dictionary The dict() constructor The dict() constructor can be used to create dictionaries from keyword arguments, or from a single iterable of key-value pairs, or from a single dictionary and keyword arguments.
A dict literal is created by surrounding a key-value list with {} 's; a keys is separated from its value with : 's, and the key : value pairs are separated with commas ( , ). An empty dict is simply {} . As with list s and tuple s, an extra , inside the {} 's is tolerated.
The dict() constructor creates a dictionary in Python. Different forms of dict() constructors are: class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg) Note: **kwarg let you take an arbitrary number of keyword arguments. A keyword argument is an argument preceded by an identifier (eg. name= ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With