⚡️ Speed up function sanitize_project_name by 48%
#26
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.
📄 48% (0.48x) speedup for
sanitize_project_nameinframework/py/flwr/cli/utils.py⏱️ Runtime :
1.58 milliseconds→1.07 milliseconds(best of350runs)📝 Explanation and details
The optimized code achieves a 47% speedup through two key optimizations:
1. Replaced Set-Based Character Filtering with Regex
The original code used a generator expression with set membership checking (
"".join(c for c in sanitized_name if c in allowed_chars)), which consumed 61.6% of the execution time. The optimized version replaces this withre.sub(r"[^a-z0-9-]", "", sanitized_name), which is significantly faster for character filtering operations. This single regex operation is more efficient than iterating through each character and checking set membership.2. Optimized Leading Character Removal
The original code used a while loop that repeatedly called
sanitized_name[0]and created new strings withsanitized_name[1:]for each invalid leading character (16.4% of execution time combined). The optimized version uses index-based iteration to find the first valid character position, then performs a single slice operationsanitized_name[i:]. This avoids repeated string allocations and reduces memory overhead.Performance Benefits by Test Case:
The optimizations maintain identical behavior while leveraging more efficient Python string operations and regex engine capabilities.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sanitize_project_name-mh182q8nand push.