⚡️ Speed up function flatten_grouping
by 330%
#3303
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.
📄 330% (3.30x) speedup for
flatten_grouping
indash/_grouping.py
⏱️ Runtime :
8.92 milliseconds
→2.07 milliseconds
(best of51
runs)📝 Explanation and details
Here is an optimized version of the provided code, focusing on reducing function call and memory overhead, inlining and shortcutting where safe, and avoiding repetitive work.
Key optimizations:
flatten_grouping
.flatten_grouping
, to avoid re-validating substructures.validate_grouping
by reusing a growing list for paths.Summary of changes and performance justifications:
flatten_grouping
is now iterative and uses an explicit stack, reducing Python call stack depth and temporary list creation.result
list in reverse order for speed but reversed once at the end for correctness.type() is ...
for speed overisinstance()
, since structure is known via schema.validate_grouping
uses index-based iteration to avoid tuple unpacking and leverages direct key traversal for dicts.This approach should result in lower CPU time due to less recursive call and reduced repeated computation, especially for large and deeply nested structures.
✅ Correctness verification report:
🌀 Generated Regression Tests Details
To edit these changes
git checkout codeflash/optimize-flatten_grouping-max6hy2z
and push.Contributor Checklist
optionals
CHANGELOG.md