My little experiments in 3.7 show exception setup is about 40% more costly
than just a do-nothing loop, but execution of is about 9x more expensive
than doing nothing, so actually very little cost if your loop only rarely
catches the exception (I assume you'll probably actually do something
inside the loop, which would reduce the proportional overhead of try-setup).
no try : 0.000022s : N= 1000 : stddev=0.00000
unraised : 0.000030s : N= 1000 : stddev=0.00005
raised : 0.000180s : N= 1000 : stddev=0.00000
from tools.timethis import timethis # Dabeaz's timing tool.
N = 1_000
for __ in range(1_000):
with timethis("no try"):
for _ in range(N):
pass
with timethis("unraised"):
for _ in range(N):
try:
pass
except ZeroDivisionError:
pass
with timethis("raised"):
for _ in range(N):
try:
raise ZeroDivisionError
except ZeroDivisionError:
pass
On Wed, Dec 4, 2019 at 9:22 PM Serhiy Storchaka
05.12.19 04:43, Andrew Barnert via Python-ideas пише:
Yes, you have to unlearn it. Exceptions are not that expensive in Python (and in a lot of other modern languages)—but even if they were, you’d still have to deal with the fact that Python uses them pervasively. Every for loop ends with an exception being thrown and caught, whether you like it or not.
Raising and catching an exception in the C code is much cheaper than in the Python code. In Python you instantiate an exception and set its traceback, context and clause, in C you can just store several threadlocal pointers (most of them NULLs). In python you execute complex bytecode to catch an exception, in C you just read and compare few pointers in common case. StopIteration is not even raised in most case internally in the C code, it is raised only when leaked to the Python code.
So exceptions are still expensive in Python, even comparing with other Python code. But outside of tight loops or if you do some input/output, they are proper tool for control flow. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/KRBXAR... Code of Conduct: http://python.org/psf/codeofconduct/