Why don't you measure it using the timeit module ? This way you can find out if this applies to your application.
OK, so I just tried the following:
import timeit statements=["""\ try: b = 10/a except ZeroDivisionError: pass""", """\ if a: b = 10/a""", "b = 10/a"] for a in (1,0): for s in statements: t = timeit.Timer(stmt=s, setup='a={}'.format(a)) print("a = {}\n{}".format(a,s)) print("%.2f usec/pass\n" % (1000000 * t.timeit(number=100000)/100000))
Result:
a = 1 try: b = 10/a except ZeroDivisionError: pass 0.25 usec/pass a = 1 if a: b = 10/a 0.29 usec/pass a = 1 b = 10/a 0.22 usec/pass a = 0 try: b = 10/a except ZeroDivisionError: pass 0.57 usec/pass a = 0 if a: b = 10/a 0.04 usec/pass a = 0 b = 10/a ZeroDivisionError: int division or modulo by zero
So, as expected, the absence of an exception handler is a little faster (but it will explode on your face when an exception occurs), and try/except faster than the explicit if , until the condition is met.
But all this is in the same order and hardly matters in any case. Only if the condition is indeed met does the if version execute much faster.
Tim Pietzcker Mar 26 '10 at 8:54 2010-03-26 08:54
source share