简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM