⚡️ Speed up function to_custom_raw_response_wrapper by 10%
#25
+6
−1
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.
📄 10% (0.10x) speedup for
to_custom_raw_response_wrapperinsrc/openai/_response.py⏱️ Runtime :
98.3 microseconds→89.6 microseconds(best of564runs)📝 Explanation and details
The optimization eliminates unnecessary dictionary copying and casting operations when handling the
extra_headersparameter.Key Changes:
Removed expensive dictionary unpacking: The original code used
{**(cast(Any, kwargs.get("extra_headers")) or {})}which always creates a new dictionary via unpacking, even whenextra_headersis already a valid dict.Added conditional copying logic: The optimized version checks if
extra_headersis None (creates empty dict), or if it's not already a dict type (converts to dict), otherwise uses the existing dict directly.Eliminated unnecessary cast operation: Removed the
cast(Any, ...)wrapper which added overhead without functional benefit.Why This Is Faster:
{**dict}) is computationally expensive as it iterates through all key-value pairs to create a new dictionaryextra_headersis None or not a dict)Performance Characteristics:
The optimization shows consistent 7-13% speedups across all test cases, with particularly strong performance when:
extra_headersis already a dict (most common case) - avoids unnecessary copyingThe 9% overall speedup comes from reducing the most common code path from "always copy" to "copy only when needed."
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-to_custom_raw_response_wrapper-mhcx7bnfand push.