How much of a difference are these two as far as performance?
tmp = []
tmp.append(True)
print tmp[0]
And
tmp = {}
tmp[0] = True
print tmp[0]
It is more efficient to use dictionaries for the lookup of elements as it is faster than a list and takes less time to traverse. Moreover, lists keep the order of the elements while dictionary does not. So, it is wise to use a list data structure when you are concerned with the order of the data elements.
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.
It is well-known that in Python tuples are faster than lists, and dicts are faster than objects.
Dictionary occupies much more space than a list of tuples. Even an empty dict occupies much space as compared to a list of tuples. Example 1: As we can clearly see that there is a huge difference between memory consumption of both the datatypes when both are empty.
Not only is micro-optimization usually pointless in general, I find it is especially difficult and arcane for Python in particular. It is very easy to actually make your code simultaneously slower and more complicated. See this Stack Overflow question for an example where the simplest, clearest, and shortest Python solutions also turned out to be the fastest.
As others have shown with actual tests, the speed difference between your two choices is quite small. What is less small is the semantic difference. Lists and dictionaries are not merely two implementations of the same concept, but are intended for different uses. Pick the one which better fits your use.
The timeit
module in the standard library is designed just to answer such questions! Forget the print
(which would have the nasty side effect of spewing stuff to your terminal;-) and compare:
$ python -mtimeit 'tmp=[]; tmp.append(True); x=tmp[0]'
1000000 loops, best of 3: 0.716 usec per loop
$ python -mtimeit 'tmp={}; tmp[0]=True; x=tmp[0]'
1000000 loops, best of 3: 0.515 usec per loop
So, the dict is the winner -- by 0.2 microseconds...!-)
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