⚡️ Speed up function _is_ui_route by 239%
#435
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.
📄 239% (2.39x) speedup for
_is_ui_routeinlitellm/proxy/auth/auth_checks.py⏱️ Runtime :
189 milliseconds→55.9 milliseconds(best of70runs)📝 Explanation and details
The optimization achieves a 238% speedup by eliminating the primary performance bottleneck: repeated regex compilation in route pattern matching.
Key Optimizations:
Regex Compilation Caching: The original code compiled the same regex patterns repeatedly via
re.sub()andre.match()on every call to_route_matches_pattern(). The optimized version introduces@lru_cache(maxsize=128)on_get_compiled_route_regex()to cache compiled regex objects, avoiding expensive recompilation for repeated patterns.Single-Pass Route Checking: The original
_is_ui_route()used two separateany()loops - first checkingstartswith()matches, then pattern matches. The optimization combines both checks into a single loop with short-circuit logic, reducing iterations overallowed_routesfrom 2N to N operations.Performance Impact:
_route_matches_pattern()time dropped from 713ms to 206ms (71% reduction)_is_ui_route()execution time by 42%Workload Benefits:
Based on
function_references,_is_ui_route()is called from_is_allowed_route()for every UI token validation request. This optimization is particularly valuable for:/threads/{thread_id}where regex compilation overhead is significantThe caching approach is especially effective since UI routes typically follow predictable patterns that repeat across requests, making the LRU cache highly efficient.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_is_ui_route-mhwtfox3and push.