From: bwarsaw at cnri.reston.va.us (Barry A. Warsaw)
Date: Thu, 22 Apr 1999 23:31:33 -0400 (EDT)
Subject: try vs. has_key()
References: <aahzFAM4oJ.M7M@netcom.com>
	<371FC9A7.D3C77413@bioreason.com>
Message-ID: <14111.59797.258298.283889@anthem.cnri.reston.va.us>
Content-Length: 1095
X-UID: 811                                                  

>>>>> "AD" == Andrew Dalke <dalke at bioreason.com> writes:

    AD> Barry's results showed that if 5% of the cases or
    AD> less were "exceptional" then try/except is faster, otherwise,
    AD> use has_key.  Alas, I cannot find the URL for that paper.

<http://www.python.org/~bwarsaw/ecshort.pdf> (sorry, I lost the
on-line version of the longer paper)

I did the tests as part of my presentation at IPC6, against Python
1.5.  While the numbers and exact trade-off might be different now, I
believe the general recommendations are still valid.  If you expect to
get a hit on the key less than ~90% of the time, use has_key().  The
one pattern where you might be better off with try/except would be if
you're using a dictionary as a cache, where you'll only get a miss
once.

Note that since then, dictionaries grew a get() method, which will
usually be better than both has_key() and try/except, depending on the
application.  E.g.:

    dict[counterkey] = dict.get(counterkey, 0) + 1

With only one dictionary access and no exceptions, this is about as
fast as you're gonna get.

-Barry




