In another question, the accepted answer suggested replacing a (very cheap) if statement in Python code with a try/except block to improve performance.
Coding style issues aside, and assuming that the exception is never triggered, how much difference does it make (performance-wise) to have an exception handler, versus not having one, versus having a compare-to-zero if-statement?
Why don’t you measure it using the
timeitmodule? That way you can see whether it’s relevant to your application.OK, so I’ve just tried the following (using Python 3.11.1 on Windows 11):
Result:
As you can see, there is not much of a difference between using a
try/exceptclause vs. an explicitifstatement, unless the exception gets triggered. (And of course, not having any control structure is fastest, though not by much, and it will crash the program if anything goes wrong).Compare this to the results obtained in 2010:
I appears that the PC I’m using now is about twice as fast as the one I had back then. The cost of handling an Exception appears identical, and the "normal" operations (arithmetic) have been improved even more than the handling of control structures, but the point from all those years ago still stands:
It’s all within the same order of magnitude and unlikely to matter either way. Only if the condition is actually met (often), then the
ifversion is significantly faster.