Opened 10 days ago

Last modified 3 days ago

#35407 new Cleanup/optimization

Cache Model._meta.swapped

Reported by: Adam Johnson Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
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 (3)

comment:1 by Natalia Bidart, 10 days ago

Triage Stage: UnreviewedAccepted

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?

comment:2 by Natalia Bidart, 10 days ago

Needs tests: set

comment:3 by Adam Johnson, 3 days ago

Needs tests: unset
Note: See TracTickets for help on using tickets.
Back to Top