⚡️ Speed up method MockRequest.get_host by 1,051%
#43
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.
📄 1,051% (10.51x) speedup for
MockRequest.get_hostinsrc/requests/cookies.py⏱️ Runtime :
1.60 milliseconds→139 microseconds(best of334runs)📝 Explanation and details
The optimization eliminates redundant URL parsing by caching the parsed result during initialization. The original code called
urlparse(self._r.url)twice - once in__init__to get the scheme and again inget_host()to get the netloc. The optimized version parses the URL only once in__init__, storing bothparsed_url.schemeandparsed_url.netloc(asself._host) for future use.This change provides a 35x speedup (from 6.9μs to 195ns per
get_host()call) because:urlparse()function performs string analysis, regex matching, and object creationget_host()now return a pre-computed value instead of re-parsingself._hostis a simple attribute lookup vs. full URL parsingThe optimization is particularly effective for scenarios where:
get_host()is called multiple times on the same MockRequest instanceAll test cases show consistent 8-15x speedups, demonstrating the optimization works across different URL formats (IPv4/IPv6, various schemes, with/without ports, etc.) without changing behavior.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-MockRequest.get_host-mgq48567and push.