Opened 7 months ago
Closed 6 months ago
#35407 closed Cleanup/optimization (fixed)
Cache Model._meta.swapped
Reported by: | Adam Johnson | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Ready for checkin | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Another candidate for caching, like #35232 before.
The Model._meta.swapped
property returns the model that this one has been swapped for. Since most models are not swappable (only auth.User
is officially swappable), it returns None
in nearly all cases.
I found this property was the most called function in Django when profiling a subset of Django’s tests, with:
$ python -m cProfile -o profile runtests.py --parallel 1 *model* $ python -m pstats profile <<< 'sort ncalls stats 10000' | less
This showed 439,484 calls to swapped
, taking 29ms of the 5.597s test run, or 0.5% of the total runtime.
After adding @cached_property
, this is reduced to 3,653 calls, rounding down to 0ms.
Change History (5)
comment:1 by , 7 months ago
Triage Stage: | Unreviewed → Accepted |
---|
comment:2 by , 7 months ago
Needs tests: | set |
---|
comment:3 by , 7 months ago
Needs tests: | unset |
---|
comment:4 by , 6 months ago
Triage Stage: | Accepted → Ready for checkin |
---|
Thank you Adam! I a little on the fence on this one but let's give it a chance. Could you please a test in the PR to cover for the new (non trivial) logic?