⚡️ Speed up method Mount.matches by 24%
#10
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
Mount.matchesinstarlette/routing.py⏱️ Runtime :
106 microseconds→85.0 microseconds(best of28runs)📝 Explanation and details
The optimized version achieves a 24% speedup through several key micro-optimizations that reduce overhead in the hot path of route matching:
Key Optimizations:
Reduced dictionary lookups: Caches
scope["type"]in a local variable and replaces theinoperator check with explicit equality comparisons (scope_type == "http" or scope_type == "websocket"), eliminating tuple creation and membership testing overhead.Optimized parameter conversion loop: Instead of iterating over
matched_params.items()and doing dictionary lookups for each key-value pair, it extracts the "path" parameter first withpop(), then iterates only over remaining keys. This reduces the number of dictionary operations and avoids converting the path parameter twice.Local variable caching: Stores
self.param_convertorsin a local variableconvertorsto avoid repeated attribute lookups during the conversion loop.Conditional path_params handling: Instead of always calling
dict(scope.get("path_params", {}))which creates a new dictionary, it checks if existing path_params exist first. If none exist, it directly usesmatched_params; if they exist, it uses the more efficient.copy()method.Reduced scope.get() calls: Pre-fetches
app_root_pathvalue instead of embedding thescope.get()call directly in the dictionary construction.Performance Impact by Test Case:
The optimizations show consistent improvements across all test scenarios:
The optimizations are particularly effective for common HTTP/WebSocket routing scenarios with path parameters, where the reduced dictionary operations and more efficient parameter processing provide measurable gains.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Mount.matches-mhbmqcm5and push.