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

Sybren Stuvel sybrenUSE at YOURthirdtower.com.imagination
Sun Jul 10 16:28:39 EDT 2005


Steve Juranich enlightened us with:
> 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". 

Then here is the counter argument:

- Starting a 'try' is, as said somewhere else in this thread, a single
  bytecode, hence simple.

- Those old-timers will probably check the data before they pass it to
  a function. Because their function has to be stable and idiot-proof
  as well, the function itself performs another check. Maybe the data
  is passed even further down a function chain, making checks before
  and after the function calls. After all, we want to be sure to only
  call a function when we're sure it won't fail, and every function
  has to gracefully bail when it's being passed bad data.

This means that there will be a _lot_ of checks in the code. Now
compare this by setting up a single try-block, and catching the
exception at the proper place in case it's being thrown.

The important part is this: those old-timers' "if" statements are
always executed - it doesn't matter whether the data is correct or
incorrect. The "heavy" part of exceptions only comes into play when
the data is incorrect, which by proper design of the program shouldn't
happen often anyway.

As far as I see it, try/except blocks are "cheaper" than "if"
statements.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
                                             Frank Zappa



More information about the Python-list mailing list