Tuples are faster than lists. We should use a Tuple instead of a List if we are defining a constant set of values and all we are ever going to do with it is iterate through it. If we need an array of elements to be used as dictionary keys, we can use Tuples.
A dictionary is 6.6 times faster than a list when we lookup in 100 items.
It is well-known that in Python tuples are faster than lists, and dicts are faster than objects.
The reason is because a dictionary is a lookup, while a list is an iteration. Dictionary uses a hash lookup, while your list requires walking through the list until it finds the result from beginning to the result each time.
There are a couple of ways to construct a dictionary in python, for example:
keyvals = [('foo', 1), ('bar', 'bar'), ('baz', 100)]
dict(keyvals)
and
dkwargs = {'foo': 1, 'bar': 'bar', 'baz': 100}
dict(**dkwargs)
When you benchmark these
In [0]: %timeit dict(keyvals)
667 ns ± 38 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [1]: %timeit dict(**dkwargs)
225 ns ± 7.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
you see that the first method is almost 3x slower than the second. Why is this?
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