⚡️ Speed up method MigrationQuestioner.ask_not_null_alteration by 6%
#117
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 6% (0.06x) speedup for
MigrationQuestioner.ask_not_null_alterationindjango/db/migrations/questioner.py⏱️ Runtime :
337 microseconds→319 microseconds(best of161runs)📝 Explanation and details
The optimization replaces
defaults or {}andspecified_apps or set()with explicitNonechecks usingif x is not None else ...in the__init__method.Key Change: Instead of relying on Python's truthiness evaluation (where
orcreates new objects even when the left operand is falsy but notNone), the optimized version only creates new empty containers when the parameter is actuallyNone.Why It's Faster: The
oroperator always evaluates both operands and creates new objects ({}andset()) on every instantiation. The explicitNonecheck avoids unnecessary object creation when non-Nonevalues are passed, even if they're falsy (like empty dicts or sets). This reduces memory allocation overhead and interpreter work.Performance Pattern: The optimization shows consistent gains in scenarios with multiple instantiations (
test_large_scale_many_calls: 5.5-7.1% faster,test_returns_none_with_multiple_instances: 6.13% faster) where the reduced object creation accumulates. Individual method calls toask_not_null_alterationshow mixed but generally positive results, likely due to reduced initialization overhead when the questioner instances are created during testing.This optimization is particularly effective for classes that are frequently instantiated, as it eliminates redundant object creation during initialization.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-MigrationQuestioner.ask_not_null_alteration-mh6lydvtand push.