I was wondering why the try-except is slower than the if in the program below.
def tryway():
try:
while True:
alist.pop()
except
Just thought to toss this into the mix:
I tried the following script below which seems to suggest that handling an exception is slower than handling an else
statement:
import time
n = 10000000
l = range(0, n)
t0 = time.time()
for i in l:
try:
i[0]
except:
pass
t1 = time.time()
for i in l:
if type(i) == list():
print(i)
else:
pass
t2 = time.time()
print(t1-t0)
print(t2-t1)
gives:
5.5908801555633545
3.512694835662842
So, (even though I know someone will likely comment upon the use of time
rather than timeit
), there appears to be a ~60% slow down using try/except in loops. So, perhaps better to go with if/else
when going through a for loop of several billion items.