We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

How fast are exceptions?

Adding try/except statements doesn’t affect performance much. Actually raising and catching an exception is rather expensive, though. When performance is important, it’s often worth testing for a condition, instead of relying on exceptions.

For example, here’s a common idiom for using a dictionary as a cache:

    value = dict[key]
except KeyError:
    value = dict[key] = getvalue(key)

This is only optimal when you expect the dictionary to have the key most of the time. If that isn’t the case, it’s more efficient to do an extra dictionary lookup first:

if key in dict:
    value = dict[key]
    value = dict[key] = getvalue(key)

When in doubt, benchmark the two alternatives on real data before you decide which one to use.

CATEGORY: general