⚡️ Speed up function all_valid by 77%
#211
Open
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.
📄 77% (0.77x) speedup for
all_validindjango/forms/formsets.py⏱️ Runtime :
507 microseconds→286 microseconds(best of194runs)📝 Explanation and details
The optimization removes the unnecessary list comprehension wrapper around the generator expression passed to
all().Key Change:
all([formset.is_valid() for formset in formsets])- creates a full list in memoryall(formset.is_valid() for formset in formsets)- uses a generator expressionWhy it's faster:
all()encounters the firstFalsevalue, it can immediately returnFalsewithout evaluating remaining formsets or building the complete listPerformance characteristics based on tests:
Falsevalues allow short-circuiting (e.g.,test_all_valid_large_one_false_at_startshows 2581% speedup)The optimization is particularly effective for large formset collections with early invalid entries, where the generator can terminate early rather than building a complete list of boolean results.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-all_valid-mhcvw8r3and push.