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

corey.coughlin at comcast.net corey.coughlin at comcast.net
Mon Jul 11 20:50:12 EDT 2005


It really does depend.  For instance, some other programmers where I
work came up with a way to represent a hierarchical, somewhat random
data set by creating each object and then adding attributes to those
for each subobject, and so on down the tree.  However, you could never
really be sure that the object you wanted was really there, so for
every access call they just wrapped it in a try ...except loop.  Now
that may seem like a good way to go, but when I rewrote some code to
use hasattr() instead, it ran a lot faster.  So yeah, exceptions can be
handy, but if you code requires exception handling for everything, you
may want to rethink things.

Steve Juranich wrote:
> I know that this topic has the potential for blowing up in my face,
> but I can't help asking.  I've been using Python since 1.5.1, so I'm
> not what you'd call a "n00b".  I dutifully evangelize on the goodness
> of Python whenever I talk with fellow developers, but I always hit a
> snag when it comes to discussing the finer points of the execution
> model (specifically, exceptions).
>
> 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".  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."
>
> I was wondering how true this holds for Python, where exceptions are
> such an integral part of the execution model.  It seems to me, that if
> I'm executing a loop over a bunch of items, and I expect some
> condition to hold for a majority of the cases, then a "try" block
> would be in order, since I could eliminate a bunch of potentially
> costly comparisons for each item.  But in cases where I'm only trying
> a single getattr (for example), using "if" might be a cheaper way to
> go.
>
> 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.
>
> Could you please tell me if I'm even remotely close to understanding
> this correctly?
> -- 
> Steve Juranich
> Tucson, AZ
> USA




More information about the Python-list mailing list