⚡️ Speed up function sanitize_filename by 31%
#73
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.
📄 31% (0.31x) speedup for
sanitize_filenameinskyvern/forge/sdk/api/files.py⏱️ Runtime :
539 microseconds→411 microseconds(best of250runs)📝 Explanation and details
The optimization achieves a 31% speedup by making two key changes that improve both membership checking and string construction performance:
What was optimized:
["-", "_", ".", "%", " "]with a pre-created set{"-", "_", ".", "%", " "}, improving character lookup from O(n) to O(1) complexity.str.join(), reducing function call overhead.Why this leads to speedup:
c in allowed, Python must scan through each element in a list (5 comparisons worst-case), but with a set it uses hash-based lookup (constant time). For longer filenames with many characters to filter, this compounds significantly.str.join(), providing a small but consistent performance gain.Performance patterns from tests:
Impact on workloads:
Based on the function references,
sanitize_filenameis called in file download/upload workflows (download_file,rename_file,create_named_temporary_file). These are likely I/O-bound operations where even microsecond improvements in filename processing can reduce overall latency, especially when processing many files or files with complex names containing special characters.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sanitize_filename-mi7cfqefand push.