unintuitive dict timings
Bob van der Poel
bvdpoel at kootenay.com
Sun Oct 12 14:56:17 EDT 2003
There was a thread a few days ago about populating a dict/list. I've got
a bit of bottleneck in my program so grabbed the ideas and did a timing
test....
----------
import time
import random
# Test of various methods to add an item to a list in a dict.
def ifelse(key, val):
if d.has_key(key):
d[key].append(val)
else:
d[key]=[val]
def get1(key,val):
l=d.get(key) or []
l.append(val)
d[key]=l
def get2(key,val):
l=d.get(key, [])
l.append(val)
d[key]=l
for p in (ifelse, get1, get2):
tm=time.clock()
d={}
kc=1000
print "Function: %s Keycount %s" % (p, kc)
for t in range(100000):
key=random.randrange(kc)
val=random.randrange(999)
p(key,val)
print "Time", time.clock()-tm
------------
Before running, my thoughts were that get2() would have been the fastest
(due to the fact there were less statements) and ifelse() would have
been the slowest. Surprisingly (to me) ifelse() is the fastest() and
get2() is the slowest.
Which begs the question...is there a faster way? BTW, interesting (again
to me) that the most readable is also the fastest.
--
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: bvdpoel at kootenay.com
WWW: http://www.kootenay.com/~bvdpoel
More information about the Python-list
mailing list