Opened 14 minutes ago
#37545 new Uncategorized
Quadratic _get_altered_foo_together_operations("index_together") calls in MigrationAutodetector.
| Reported by: | djrobstep | Owned by: | |
|---|---|---|---|
| Component: | Migrations | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
In django/db/migrations/autodetector.py, MigrationAutodetector.create_altered_indexes() iterates over every model in sorted(self.kept_model_keys) and, inside that loop, calls self._get_altered_foo_together_operations(operations.AlterIndexTogether.option_name):
for app_label, model_name in sorted(self.kept_model_keys): ... for ( old_value, new_value, index_together_app_label, index_together_model_name, dependencies, ) in self._get_altered_foo_together_operations( operations.AlterIndexTogether.option_name ): if ( app_label != index_together_app_label or model_name != index_together_model_name ): continue ...
_get_altered_foo_together_operations() itself sorts and iterates over all of self.kept_model_keys, making create_altered_indexes() O(models2). This runs on every makemigrations invocation and on every migrate invocation (which runs the autodetector to check for unmigrated model changes).
Nothing read by _get_altered_foo_together_operations() (from_state, to_state, kept_model_keys, renamed_models, renamed_fields) is modified during the loop.
Impact
- Synthetic benchmark (autodetecting changes between two 1,000-model states): 0.70s on
mainvs 0.28s after hoisting the call out of the loop.
Proposed fix
Call self._get_altered_foo_together_operations(operations.AlterIndexTogether.option_name) once before the for app_label, model_name in sorted(self.kept_model_keys): loop, grouping the results by (app_label, model_name). This preserves detection of historical index_together → Meta.indexes renames while reducing the loop from O(N2) to O(N).
I have a patch with regression tests ready and will open a PR referencing this ticket.