actix-web
                                
                                 actix-web copied to clipboard
                                
                                    actix-web copied to clipboard
                            
                            
                            
                        Refactor and Optimization of Match Resource Definition
PR Type
Feature / Refactor
PR Checklist
- [x] Tests for the changes have been added / updated.
- [x] Documentation comments have been added / updated.
- [x] A changelog entry has been made for the appropriate packages.
- [x] Format code with the latest stable rustfmt.
- [x] (Team) Label with affected crates and semver status.
Overview
Current Behavior
Currently, to check if a resource matches a definition using capture_match_info_fn, we always need to pass a function to perform additional checks.
This causes two problems:
- The check function is called inside the capture_match_info_fn, so we cannot determine if fails on the check or matching part.
- If the caller doesn't want to perform any extra checks, they still have to pass a dummy closure.
New Behavior
The capture_match_info function was refactored into the following components:
- resolve_path() -> Processes the resource match information (Path Length and Dynamic Segments) using the resource definition.
- resolve_path_if_match() -> Checks if a resource matches resource definition and, if so, calls resolve_path() to extract perform path processing
- capture_match_info(): Now solely responsible for matching a single resource against a resource definition.
Additionally, the Router Builder has been enhanced with a new mechanism to track path conflicts: When a resource definition is added, it increments a conflict counter if its path pattern matches one previously added (ignoring guards and other configurations). At the end of the build process, it computes the maximum number of path conflicts.
This enables an early return optimization in recognize_fn()—if the number of matching paths reaches the recorded conflict maximum, further checks can be skipped.
Performance Test
Old Implementation
New Implementation
After multiple test suite executions, the following performance improvements were observed:
- With Guard Check Failure: Reduced from 27µs to 10µs
- Without Guard Check Failure: Reduced from 12µs to 10µs
The performance gain in the "no guard check failed" scenario is primarily due to the elimination of unnecessary data structure initializations (specifically, segment allocations) when performing static resource path matching.
Closes #3645