#35405: Use @cached_property for FieldCacheMixin cache key -------------------------------------+------------------------------------- Reporter: Adam | Owner: Adam Johnson Johnson | Type: | Status: assigned Cleanup/optimization | Component: Database | Version: dev layer (models, ORM) | Severity: Normal | Keywords: Triage Stage: | Has patch: 1 Unreviewed | Needs documentation: 0 | Needs tests: 0 Patch needs improvement: 0 | Easy pickings: 0 UI/UX: 0 | -------------------------------------+------------------------------------- `FieldCacheMixin` is used by related fields to track their cached values. Its existing design means calling `get_cache_name()` for each operation, even though that value doesn’t change. Changing `get_cache_name()` into a cached property can thus save a bunch of small but useless function calls working with related fields.
I profiled this change by using cProfile on a selection of tests using related fields: {{{ $ python -m cProfile -s cumtime -o profile runtests.py --parallel 1 foreign_object *relat* ... Found 399 test(s). ... }}} Before, there were 12,520 function calls: {{{ $ python -m pstats profile <<< 'sort cumtime stats 10000' | rg get_cache_name 11193 0.001 0.000 0.001 0.000 /Users/chainz/Documents/Projects/django/django/db/models/fields/related.py:512(get_cache_name) 712 0.000 0.000 0.000 0.000 /Users/chainz/Documents/Projects/django/django/db/models/fields/reverse_related.py:251(get_cache_name) 615 0.000 0.000 0.000 0.000 /Users/chainz/Documents/Projects/django/django/contrib/contenttypes/fields.py:143(get_cache_name) }}} After, there are just 227 calls (should be one per related field): {{{ $ python -m pstats profile <<< 'sort cumtime stats 10000' | rg cache_name 172 0.000 0.000 0.000 0.000 /Users/chainz/Documents/Projects/django/django/db/models/fields/related.py:512(cache_name) 34 0.000 0.000 0.000 0.000 /Users/chainz/Documents/Projects/django/django/db/models/fields/reverse_related.py:251(cache_name) 21 0.000 0.000 0.000 0.000 /Users/chainz/Documents/Projects/django/django/contrib/contenttypes/fields.py:143(cache_name) }}} The time saving is minimal here. It may be notable when working with a lot of model instances. -- Ticket URL: <https://code.djangoproject.com/ticket/35405> Django <https://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-updates+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-updates/0107018f1638d8ff-e72e85c3-4164-41ce-92db-712ac77c250b-000000%40eu-central-1.amazonses.com.