slow try statements in python?

Andrew MacIntyre andymac at bullseye.apana.org.au
Wed Feb 19 05:29:50 EST 2003


On Tue, 18 Feb 2003, Greg Ewing (using news.cis.dfn.de) wrote:

> Mark Higgins wrote:
>
> > I've seen quite a few examples of python code where try statements are
> > used to control the flow of a program... seems reasonable, but with my
> > background in C++ I'm always concerned that try statements are slow.
> >
> > Is this a concern in python?
>
> Not really. Raising and catching an exception is no more
> expensive than many other things that Python programs do
> a lot of, e.g. calling methods.
>
> C++ implementations tend to be heavily optimised towards
> the case where no exceptions are raised, on the assumption
> that exceptions truly are "exceptional". But there is no
> such bias in Python -- you're meant to be able to use
> exceptions freely.

Notwithstanding this, I think you'll find that it is recognised in the
collective wisdom that try/except can be noticeably more expensive in
circumstances where an operation is repeatedly tried with a significant
likelihood of an exception, compared to other techniques.

It is not so much the "try" that is expensive, but rather the "except:"
(ie actually handling the raised exception).

In general though, as Greg notes, the difference is not worth worrying
about until you can define a requirement to optimise around it.

--
Andrew I MacIntyre                     "These thoughts are mine alone..."
E-mail: andymac at bullseye.apana.org.au  | Snail: PO Box 370
        andymac at pcug.org.au            |        Belconnen  ACT  2616
Web:    http://www.andymac.org/        |        Australia






More information about the Python-list mailing list