Skip to content

Instantly share code, notes, and snippets.

@smithdc1
Last active March 11, 2021 11:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save smithdc1/873688e563c66a0dd253602aab6fc3e2 to your computer and use it in GitHub Desktop.
Save smithdc1/873688e563c66a0dd253602aab6fc3e2 to your computer and use it in GitHub Desktop.
Benchmark of Django and Python's cached_property decorators
import pyperf
from django.utils.functional import cached_property as dj_cached_property
from functools import cached_property as py_cached_property
class TestClass:
@dj_cached_property
def dj_cached(self):
return "Test"
@py_cached_property
def py_cached(self):
return "Test"
t = TestClass()
def django_cache(loops):
range_it = range(loops)
t0 = pyperf.perf_counter()
for loop in range_it:
t.dj_cached
t.dj_cached
t.dj_cached
t.dj_cached
t.dj_cached
t.dj_cached
t.dj_cached
t.dj_cached
t.dj_cached
t.dj_cached
return pyperf.perf_counter() - t0
def python_cache(loops):
range_it = range(loops)
t0 = pyperf.perf_counter()
for loop in range_it:
t.py_cached
t.py_cached
t.py_cached
t.py_cached
t.py_cached
t.py_cached
t.py_cached
t.py_cached
t.py_cached
t.py_cached
return pyperf.perf_counter() - t0
runner = pyperf.Runner()
runner.bench_time_func("Django Cache", django_cache)
runner.bench_time_func("Python Cache", python_cache)
@smithdc1
Copy link
Author

smithdc1 commented Jan 5, 2021

python bench_cached_property.py
.....................
Django Cache: Mean +- std dev: 1.07 us +- 0.05 us
.....................
Python Cache: Mean +- std dev: 1.08 us +- 0.05 us

@ztane
Copy link

ztane commented Mar 11, 2021

Can't be bothered to register to Django Trac but, https://bugs.python.org/issue43468 might be something you'd want to consider...

@smithdc1
Copy link
Author

Thanks for highlighting this!

@ztane
Copy link

ztane commented Mar 11, 2021

You're welcome :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment