
try/except vs getattr
By: a guest on
Aug 1st, 2012 | syntax:
Python | size: 0.94 KB | hits: 23 | expires: Never
>>> timer_try_except = Timer(
... """
... item = object()
... try:
... something = item.landlord.id
... except AttributeError:
... pass
... """
... )
>>>
>>> timer_getattr = Timer(
... """
... item = object()
... def try_getattr():
... landlord = getattr(item, 'landlord', None)
... if landlord:
... pass #normally do something here
... """
... )
>>> iterations = 9999999
>>> try_except_duration = timer_try_except.timeit(iterations)
>>> getattr_duration = timer_getattr.timeit(iterations)
>>> print 'try/except Duration: %f, %% of getattr: %f%%' % (try_except_duration, (try_except_duration / getattr_duration) * 100)
try/except Duration: 11.601219, % of getattr: 606.159781%
>>> print 'getattr Duration: %f, %% of try/except: %f%%' % (getattr_duration, (getattr_duration / try_except_duration) * 100)
getattr Duration: 1.913888, % of try/except: 16.497300%