Steve Juranich wrote:

> 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.

Exactly.

> But in cases where I'm only trying a single getattr (for example),
> using "if" might be a cheaper way to go.

Relying on exceptions is faster. In the Python world, this coding style
is called EAFP (easier to ask forgiveness than permission). You can try
it out, just do something 10**n times and measure the time it takes. Do
this twice, once with prior checking and once relying on exceptions.

And JFTR: the very example you chose gives you yet another choice:
getattr can take a default parameter.

> 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.

I don't know about the implementation of exceptions but I suspect most
of what try does doesn't happen at run-time at all, and things get
checked and looked for only if an exception did occur. An I suspect that
it's machine code that does that checking and looking, not byte code.
(Please correct me if I'm wrong, anyone with more insight.)

-- 
Thomas

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to