⚡️ Speed up function get_unicode_from_response by 24%
#36
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.
📄 24% (0.24x) speedup for
get_unicode_from_responseinsrc/requests/utils.py⏱️ Runtime :
117 microseconds→94.6 microseconds(best of273runs)📝 Explanation and details
The optimization significantly improves performance by avoiding expensive header parsing for the majority of common cases. The key change is implementing a fast-path parsing approach in
get_encoding_from_headers.What changed:
content_type.lower()) to check forcharset=directly in the header stringsplit("charset=", 1)) instead of full header parsing_parse_content_type_header()function for complex headers that the fast-path cannot handleWhy this is faster:
The original code always called
_parse_content_type_header()which does comprehensive parameter parsing with multiple string operations, dictionary building, and edge case handling. The line profiler shows this function consumed 73% of the total execution time in the original version.The optimization reduces this to just 9.7% for the 3 cases that still need full parsing, while handling 20 out of 23 test cases with simple string operations that are much faster than full parsing.
Performance gains by test type:
The optimization is particularly effective for typical HTTP responses where charset is explicitly specified or content-type follows standard patterns.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-get_unicode_from_response-mgpvpwoland push.