⚡️ Speed up function with_content_type by 251%
#123
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.
📄 251% (2.51x) speedup for
with_content_typeinskyvern/client/core/file.py⏱️ Runtime :
1.10 milliseconds→314 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 251% speedup by eliminating expensive
cast()operations and improving control flow efficiency.Key Optimizations:
Eliminated expensive
cast()calls: The original code usedcast()on every tuple unpacking operation, which consumed 56% of total runtime (lines showing 25.7% and 30.5% in profiler). The optimized version removes these entirely, relying on Python's native tuple unpacking which is much faster.Reordered branches for common case: Moved the non-tuple check first with
if not isinstance(file, tuple), optimizing for the most common usage pattern where files are passed as raw content rather than tuples.Cached
len(file)computation: Stored the length inlen_filevariable to avoid repeatedlen()calls across the elif chain.Performance Impact by Test Case:
The optimization is particularly effective for API clients handling file uploads, where tuple-based file specifications with headers and content types are common. The elimination of
cast()overhead provides consistent performance gains across all tuple-based operations while maintaining identical functionality and type safety.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-with_content_type-mirly2hband push.