⚡️ Speed up function sanitize_filename by 32%
#156
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.
📄 32% (0.32x) speedup for
sanitize_filenameinskyvern/forge/sdk/api/files.py⏱️ Runtime :
471 microseconds→357 microseconds(best of250runs)📝 Explanation and details
The optimization replaces the repeated list creation
["-", "_", ".", "%", " "]with a pre-computed setallowedand converts the generator expression to a list comprehension. This yields a 31% speedup through two key improvements:What was optimized:
c in ["-", "_", ".", "%", " "]toc in allowedwhereallowedis a set, reducing membership testing from O(n) to O(1)join()for reduced overheadWhy this is faster:
["-", "_", ".", "%", " "]for every character comparison, resulting in O(n×m) operations where n is filename length and m is allowed character countPerformance impact by workload:
The function is called in file processing workflows (download_file, rename_file, create_named_temporary_file) where filenames are sanitized. Test results show:
This optimization is particularly valuable since file operations often process user-generated filenames that can be long or contain many invalid characters, making the O(1) set lookup highly beneficial in the file handling hot path.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sanitize_filename-mjaqkc4uand push.