Skip to content

Instantly share code, notes, and snippets.

@Dowwie
Last active November 12, 2015 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dowwie/40c73ad49f2d109a7b7c to your computer and use it in GitHub Desktop.
Save Dowwie/40c73ad49f2d109a7b7c to your computer and use it in GitHub Desktop.
Memoized Property Performance Test
import timeit
class reify(object):
def __init__(self, wrapped):
self.wrapped = wrapped
try:
self.__doc__ = wrapped.__doc__
except: # pragma: no cover
pass
def __get__(self, inst, objtype=None):
if inst is None:
return self
val = self.wrapped(inst)
setattr(inst, self.wrapped.__name__, val)
return val
class memoized_property:
"""A read-only @property that is only evaluated once."""
def __init__(self, fget, doc=None):
self.counter = 10
self.fget = fget
self.__doc__ = doc or fget.__doc__
self.__name__ = fget.__name__
def __get__(self, obj, cls):
if obj is None:
return self
result = self.fget(obj)
setattr(obj, self.__name__, result)
self.counter += 1
print(self.counter)
return result
class Test1:
def __init__(self):
self._title = 'dowwie'
@memoized_property
def title(self):
if not hasattr(self, '_title'):
self._title = 'default'
return self._title
class Test2:
def __init__(self):
self._title = 'dowwie'
@property
def title(self):
if not hasattr(self, '_title'):
self._title = 'default'
return self._title
class Test3:
def __init__(self):
self._title = 'dowwie'
@reify
def title(self):
if not hasattr(self, '_title'):
self._title = 'default'
return self._title
t1 = Test1()
t2 = Test2()
t3 = Test3()
memoized = min(timeit.repeat("t1.title", setup="from __main__ import t1", repeat=3, number=1000000))
reified = min(timeit.repeat("t3.title", setup="from __main__ import t3", repeat=3, number=1000000))
oldproperty = min(timeit.repeat("t2.title", setup="from __main__ import t2", repeat=3, number=1000000))
print('memoized: ', memoized)
print('reify: ', reified)
print('oldproperty: ', oldproperty)
Results
----------
memoized: 0.02977088201441802
reify: 0.027064872003393248
oldproperty: 0.15724623799906112
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment