⚡️ Speed up function _allowed_routes_check by 324%
#437
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.
📄 324% (3.24x) speedup for
_allowed_routes_checkinlitellm/proxy/auth/auth_checks.py⏱️ Runtime :
2.65 milliseconds→624 microseconds(best of103runs)📝 Explanation and details
The optimized code achieves a 324% speedup through two key optimizations that reduce expensive operations in the hot loop:
Key Optimizations:
Cached Enum Members Lookup: The original code repeatedly accessed
LiteLLMRoutes.__members__on every iteration (61% of total runtime). The optimized version caches this as a local variablemembers = LiteLLMRoutes.__members__outside the loop, eliminating redundant global attribute lookups.Reordered Conditional Logic: The optimized version checks for direct string equality (
allowed_route == user_route) first, before the more expensive enum membership and value lookup. Since direct matches are faster than enum operations, this puts the cheaper operation first in the conditional chain.Why This Matters:
The function is called from
allowed_routes_check()in authentication flows where users access proxy routes. Based on the test results, the optimization is particularly effective for:The line profiler shows the optimization eliminates the expensive
LiteLLMRoutes.__members__lookup (9.94ms → 0ms in total time) while maintaining identical functionality and return values across all test cases.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_allowed_routes_check-mhwuii0qand push.