Tuple vs array in hashtable Python
I have heard that tuple element take low space but can't be modify, so what is the best solution in terms of execution times:
hash = {}
hash['foo'] = [34,'foobar',[55,90]]
hash['foo'][0] = hash['foo'][0] + 17
开发者_C百科OR
hash = {}
hash['foo'] = (34,'foobar',[55,90])
hash['foo'] = (hash['foo'][0] + 17,hash['foo'][1],hash['foo'][2])
First, don't call the dictionary hash
. It shadows the built-in hash.
In both the cases, if you delete the last line and then time the code, the values are:
0.545173168182 # list
0.479876995087 # tuple
And that is expected behaviour. Because creating a tuple
is faster than creating a list.
$ python -mtimeit 'l=[]'
10000000 loops, best of 3: 0.053 usec per loop
$ python -mtimeit 't=()'
10000000 loops, best of 3: 0.026 usec per loop
But in your case, take the third line. You create a new foo
key as you can't modify the tuple
, so it will take more time than the list
example.
0.911674976349 # list
1.1165189743 # tuple
Another note, the time differences are micro-optimizations. Given the small difference, you should not worry about them.
精彩评论