⚡️ Speed up function get_actual_routes by 213%
#438
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.
📄 213% (2.13x) speedup for
get_actual_routesinlitellm/proxy/auth/auth_checks.py⏱️ Runtime :
1.43 milliseconds→455 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 213% speedup by eliminating expensive exception handling and reducing method lookup overhead in the core loop.
Key Performance Optimizations:
Replaced try/except with dictionary lookup: The original code used
LiteLLMRoutes[route_name]which throwsKeyErrorfor invalid routes, requiring expensive exception handling. The optimized version usesLiteLLMRoutes.__members__.get(route_name)which returnsNonefor missing keys without exceptions. Exception handling in Python is significantly more costly than dictionary lookups.Cached method references: The optimized code caches
actual_routes.extendandactual_routes.appendas local variables (extend_actual_routes,append_actual_routes). This eliminates repeated attribute lookups in the loop, which is especially beneficial for the large-scale test cases.Simplified value handling: Removed the unnecessary
list()conversion for sets sinceextend()accepts any iterable, including sets directly.Performance Impact Analysis:
The function is called in authentication flows (as shown in
handle_jwt.py), where route access permissions are validated. The optimization is particularly effective for:The optimizations maintain identical behavior and output while dramatically reducing CPU overhead, especially beneficial when validating admin route permissions in authentication-heavy applications.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-get_actual_routes-mhwuwo3cand push.