Opened 3 months ago

Closed 3 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 Natalia Bidart, 3 months 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, 3 months ago

Needs tests: set

comment:3 by Adam Johnson, 3 months ago

Needs tests: unset

comment:4 by Sarah Boyce, 3 months ago

Triage Stage: AcceptedReady for checkin

comment:5 by Sarah Boyce <42296566+sarahboyce@…>, 3 months ago

Resolution: fixed
Status: newclosed

In 7abe511:

Fixed #35407 -- Cached model's Options.swapped.

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