Should I use "if" or "try" (as a matter of speed)?
peter at engcorp.com
Sat Jul 9 23:42:28 CEST 2005
Thomas Lotze wrote:
> Steve Juranich wrote:
>>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.)
Part right, part confusing. Definitely "try" is something that happens
at run-time, not compile time, at least in the sense of the execution of
the corresponding byte code. At compile time nothing much happens
except a determination of where to jump if an exception is actually
raised in the try block.
Try corresponds to a single bytecode SETUP_EXCEPT, so from the point of
view of Python code it is extremely fast, especially compared to
something like a function call (which some if-tests would do). (There
are also corresponding POP_BLOCK and JUMP_FORWARD instructions at the
end of the try block, and they're even faster, though the corresponding
if-test version would similarly have a jump of some kind involved.)
Exceptions in Python are checked for all the time, so there's little you
can do to avoid part of the cost of that. There is a small additional
cost (in the C code) when the exceptional condition is actually present,
of course, with some resulting work to create the Exception object and
Some analysis of this can be done trivially by anyone with a working
interpreter, using the "dis" module.
Each line of the output represents a single bytecode instruction plus
operands, similar to an assembly code disassembly.
To go further, get the Python source and skim through the ceval.c
module, or do that via CVS
, looking for the string "main loop".
And, in any case, remember that readability is almost always more
important than optimization, and you should consider first whether one
or the other approach is clearly more expressive (for future
programmers, including yourself) in the specific case involved.
More information about the Python-list