Don't use try except when you don't need it
import time
def time_me(fnc):
def wrap(*args):
start = time.time()
r = fnc(*args)
end = time.time()
print("%s (%0.3f ms)" % (fnc.__name__, (end - start) * 1000))
return r
return wrap
@time_me
def without_try(n, gen_dict=False):
a = {i: i for i in range(n)} if gen_dict else {}
for i in range(n):
if i in a:
del a[i]
return n
@time_me
def with_try(n, gen_dict=False):
a = {i: i for i in range(n)} if gen_dict else {}
for i in range(n):
try:
del a[i]
except KeyError:
pass
iterations_n = 1000000
with_try(iterations_n) # 390.680 ms
without_try(iterations_n) # 58.157 ms
with_try(iterations_n, True) # 286.983 ms
without_try(iterations_n, True) # 291.633 ms
We can see that in edge case, where all keys exist, using try except can be slightly faster. On the other hand, when none exist, it's rapidly faster. In my opinion, it is worth checking if the key exist.
Inspired by Patrick Altman however I just wanted to save my own simpler example.