Should I use "if" or "try" (as a matter of speed)?

Roy Smith roy at panix.com
Sat Jul 9 21:06:07 CEST 2005


Steve Juranich <sjuranic at gmail.com> wrote:
> Without fail, when I start talking with some of the "old-timers"
> (people who have written code in ADA or Fortran), I hear the same
> arguments that using "if" is "better" than using "try".

Well, you've now got a failure.  I used to write Fortran on punch cards, so 
I guess that makes me an "old-timer", and I don't agree with that argument.

> I think that the argument goes something like, "When you set up a 'try' 
> block, you have to set up a lot of extra machinery than is necessary 
> just executing a simple conditional."

That sounds like a very C++ kind of attitude, where efficiency is prized 
above all else, and exception handling is relatively heavy-weight compared 
to a simple conditional.

> What do I mean by "cheaper"?  I'm basically talking about the number
> of instructions that are necessary to set up and execute a try block
> as opposed to an if block.

Don't worry about crap like that until the whole application is done and 
it's not running fast enough, and you've exhausted all efforts to identify 
algorithmic improvements that could be made, and careful performance 
measurements have shown that the use of try blocks is the problem.

Exceptions are better than returning an error code for several reasons:

1) They cannot be silently ignored by accident.  If you don't catch an 
exception, it bubbles up until something does catch it, or nothing does and 
your program dies with a stack trace.  You can ignore them if you want, but 
you have to explicitly write some code to do that.

2) It separates the normal flow of control from the error processing.  In 
many cases, this makes it easier to understand the program logic.

3) In some cases, they can lead to faster code.  A classic example is 
counting occurances of items using a dictionary:

   count = {}
   for key in whatever:
      try:
         count[key] += 1
      except KeyError:
         count[key] = 1

compared to

   count = {}
   for key in whatever:
      if count.hasKey(key):
         count[key] += 1
      else:
         count[key] = 1

if most keys are going to already be in the dictionary, handling the 
occasional exception will be faster than calling hasKey() for every one.



More information about the Python-list mailing list