unintuitive dict timings

Bob van der Poel bvdpoel at kootenay.com
Sun Oct 12 20:50:54 EDT 2003



Tim Peters wrote:
> [Bob van der Poel]
> 
>>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):
> 
> 
> That's faster as "if key in d". d.has_key needs an extra step to look up the
> method named "has_key" in the d object.

Yes, I tried the "if key in d" and discarded that. Guess it should have 
stayed in the test data.

<snip>


> Ouch.  You're timing lots of things besides what you're trying to time here.

Yes, you are 100%. Guess it doesn't pay to rush timing tests. Really, I 
was doing a quick and dirty test ... and I shouldn't have. As we all 
(should) know.

<snip>


> def getorset(key, val):
>     d.setdefault(key, []).append(val)

Okay, this is faster than get1() and get2().

Just in case anyone is interested :)

Function: <function ifelse at 0x80753ec> Keycount 1000
Time 1.05
Function: <function getorset at 0x80a5504> Keycount 1000
Time 1.44
Function: <function get1 at 0x80a553c> Keycount 1000
Time 1.31
Function: <function get2 at 0x80a5574> Keycount 1000
Time 1.68

So, that still leaves the most readable as the quickest...

-- 
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