try vs. has_key()

Barry A. Warsaw bwarsaw at cnri.reston.va.us
Thu Apr 22 23:31:33 EDT 1999


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




More information about the Python-list mailing list