Thoughts Serializer

Exceptions and execution speed

This post was triggered by a comment by Alex Hunsley on the Multithreaded Game Scripting post.

Alex correctly points out that while setting up a “try” for an exception costs nothing, raing an exception does! The question however is whether using exceptions is a speed overkill in the altar of code readability

It turns out that once again the answer is the wildcard answer : “It depends!…”

Lets examine the two posibilities for getting a value from a dictionary in python. First lets look at the version that uses exceptions :

try:
    value = data[key]
except KeyError:
    value = default

And the equivalent without exceptions :

if key in data:
    value = data[key]
else:
    value = default

If the key is the dictionary 99% of the time then the version that uses exceptions is the fastest you can do. There is no overhead to check if the key is in. While the second version will waste time checking for something that will 99% be there.

However if the is not likely to by the dictionary the cost of raising exceptions will make the second version faster.

So when an exception is a non common thing to occur, it is wise to use exceptions! In a game most of the events happen rarely compared to how many time a piece of code runs. So exceptions as events will not only make code easier to read, but faster too, since it will remove unecessary checks.