⚡️ Speed up method Route.matches by 13%
          #8
        
          
      
  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.
  
    
  
    
📄 13% (0.13x) speedup for
Route.matchesinstarlette/routing.py⏱️ Runtime :
328 microseconds→290 microseconds(best of74runs)📝 Explanation and details
The optimization achieves a 12% speedup by eliminating the expensive
get_route_pathfunction call in the hot path and optimizing dictionary operations in thematchesmethod.Key optimizations:
Inlined route path extraction: Instead of always calling
get_route_path(), the code directly extractspathfromscopeand only falls back to the function when necessary (whenpathis None orroot_pathexists). This eliminates ~52% of the original runtime spent on the function call.Optimized path_params handling: Rather than always creating a new dictionary with
dict(scope.get("path_params", {})), the code now only creates a copy whenpath_paramsalready exists in scope. When no existing path_params are present, it directly assignsmatched_params, avoiding unnecessary dictionary creation and update operations.Improved methods set construction: In
__init__, replaced set comprehension{method.upper() for method in methods}with explicit loop-based construction, which is slightly more efficient for small collections.The optimizations are particularly effective for:
The performance gains are consistent across different route patterns, with the largest improvements seen in parameter-heavy routes where both optimizations provide cumulative benefits.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Route.matches-mhbm0x0gand push.