⚡️ Speed up method OrderBy.get_source_expressions by 10%
#731
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.
📄 10% (0.10x) speedup for
OrderBy.get_source_expressionsindjango/db/models/expressions.py⏱️ Runtime :
350 microseconds→318 microseconds(best of212runs)📝 Explanation and details
The optimization introduces two key performance improvements:
__slots__declaration: Added__slots__ = ('nulls_first', 'nulls_last', 'descending', 'expression')to the class. This eliminates the instance dictionary (__dict__) normally used to store object attributes, reducing memory overhead and making attribute access faster. This is particularly beneficial for classes that are instantiated frequently.Tuple instead of list in
get_source_expressions(): Changedreturn [self.expression]toreturn (self.expression, ). Creating a tuple is more efficient than creating a list because:The line profiler results show the
get_source_expressions()method improved from 217.5ns per call to 188ns per call (13.5% improvement), and the overall runtime improved by 10% (350μs → 318μs).These optimizations are especially effective for the test scenarios shown, where:
The changes maintain complete behavioral compatibility while providing meaningful performance gains for Django ORM query construction, where OrderBy objects are frequently created and accessed.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-OrderBy.get_source_expressions-mh36uq4dand push.