⚡️ Speed up function create_named_temporary_file by 43%
#157
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.
📄 43% (0.43x) speedup for
create_named_temporary_fileinskyvern/forge/sdk/api/files.py⏱️ Runtime :
4.93 milliseconds→3.45 milliseconds(best of122runs)📝 Explanation and details
The optimized code achieves a 42% speedup through two targeted optimizations that address the most expensive operations identified in the profiler:
Key Optimizations:
Precomputed character set in
sanitize_filename: The original code recreated a list["-", "_", ".", "%", " "]on every call (line taking 5798ns per hit). The optimization precomputes this as a module-level set_SANITIZE_ALLOWED, reducing lookup time from O(n) list scanning to O(1) set membership. Additionally, switching from a generator expression to list comprehension provides ~10% better performance for string processing.Fast-path directory existence check in
create_folder_if_not_exist: The original code always calledPath.mkdir()which involves filesystem operations (79.9% of function time). The optimization addsos.path.isdir()as a fast-path check, avoiding expensivemkdircalls when the directory already exists. This is particularly impactful since the profiler shows this function consuming 36% of total runtime increate_named_temporary_file.Performance Impact Analysis:
Based on function references,
create_named_temporary_fileis called in critical paths including:The test results show consistent speedups across all scenarios:
The optimizations are most effective when:
These improvements directly benefit the browser automation workflow where temporary files are frequently created for downloads, session management, and artifact processing.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-create_named_temporary_file-mjar0mcoand push.