Python dictionary of dict traverses four methods of performance test reports

  • 2020-04-02 13:45:43
  • OfStack

In python, there are four ways to traverse dict. But what about the performance of these four traverses? I did the following test


l = [(x,x) for x in xrange(10000)]
d = dict(l)

from time import clock

t0=clock()
for i in d:
 t = i + d[i]
t1=clock()

for k,v in d.items():
 t = k + v
t2=clock()

for k,v in d.iteritems():
 t = k + v
t3=clock()

for k,v in zip(d.iterkeys(),d.itervalues()):
 t = k + v
t4=clock()

print t1-t0, t2-t1, t3-t2, t4-t3

Run this script 5 times and the result is as follows:


python test.py
0.00184039735833 0.00326492977712 0.00214993552657 0.00311549755797

python test.py
0.00182356570728 0.00339342506446 0.00234863111466 0.00321566640817

python test.py
0.00185107108827 0.00324563495762 0.00211175641563 0.00313479237748

python test.py
0.0018215130669 0.00320950848705 0.00215814608806 0.00322798225041

python test.py
0.00216635664955 0.00391807994377 0.00207604047314 0.00322757172233

Obviously the first method is the most efficient, the third method is a little bit worse but not much different, and method 24 has much worse performance
But the actual difference isn't too great to worry about


Related articles: