In python, if we want to check whether one element exists in a dictionary or not, try
can be used like that,
try:
mydict["condition"]
except:
raise Exception("not exist")
Also, more elegant way to do that is defensive programming.
if "condition" in mydict:
mydict["condition"]
else:
raise Exception("not exist")
And, I think the try exception
can cause software interruption, so the performance can be bad.
However, with the following test codes, it seems that try except
can improve the performance.
import time
# count the executive time
def count_time(func):
def wrap(*args):
start = time.time()
func(*args)
end = time.time()
print "func:%s time:(%0.3f ms)" % (func.func_name, (end-start) * 1000)
return wrap
@count_time
def exists_use_coarse_try(maxval):
dict_list = {"something":"...."}
try:
for item in range(0, maxval):
dict_list["something"]
except:
pass
@count_time
def not_use_try_fair(maxval):
dict_list = {"something":"...."}
for item in range(0, maxval):
if "do_something" in dict_list :
dict_list["something"]
else:
raise Exception("I know it exists!")
def run(maxval):
print "maxval:%s" % maxval
exists_use_coarse_try(maxval)
not_use_try_fair(maxval)
if __name__ == "__main__":
run(10000000)
The result is
maxval:10000000
func:exists_use_coarse_try time:(901.000 ms)
func:not_use_try_fair time:(1121.000 ms)
My question is: Is the try except
can improve the performance in Python?