⚡️ Speed up method Host.matches by 66%
#11
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.
📄 66% (0.66x) speedup for
Host.matchesinstarlette/routing.py⏱️ Runtime :
2.23 milliseconds→1.35 milliseconds(best of5runs)📝 Explanation and details
The optimized version achieves a 65% speedup by eliminating expensive object allocations and method lookups in the hot path:
Key optimizations:
Direct header parsing: Instead of creating a
Headersobject on every request, the code directly iterates through the rawscope["headers"]list to find the host header. This avoids object instantiation and the overhead of the Headers class's generic lookup mechanism.Cached bound method: The
self.host_regex.matchmethod is cached asself._host_regex_matchduring initialization, eliminating repeated attribute lookups in the hot loop.Optimized parameter conversion:
convertors = self.param_convertorsto avoid repeated attribute accessEfficient path_params handling: Uses dict unpacking (
{**path_params, **matched_params}) instead ofdict()constructor +update()calls, and conditionally creates the merged dict only when existing path_params exist.Performance characteristics based on tests:
The optimization is most effective for typical web traffic patterns where host headers are consistently present and parameter counts are moderate.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Host.matches-mhbpin64and push.