⚡️ Speed up function is_model_allowed_by_pattern by 1,026%
#447
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.
📄 1,026% (10.26x) speedup for
is_model_allowed_by_patterninlitellm/proxy/auth/auth_checks.py⏱️ Runtime :
21.6 milliseconds→1.92 milliseconds(best of5runs)📝 Explanation and details
The optimization adds compiled regex caching to eliminate redundant regex compilation overhead. Instead of calling
re.match()with a string pattern (which compiles the regex on every call), the optimized version:re.compile()and stores them in a module-level cache_pattern_cacheKey Performance Impact:
re.compile) now only happens 545 times instead of 4,086 times (87% reduction)re.match()call becomes significantly faster when using pre-compiled patternsWhy This Works:
Regex compilation is computationally expensive, involving parsing the pattern string and building a finite state machine. When the same wildcard patterns are used repeatedly (common in auth scenarios), caching the compiled regex objects eliminates this repeated overhead.
Real-World Benefits:
Based on the function references,
is_model_allowed_by_patternis called within loops in_model_matches_any_wildcard_pattern_in_list(), making it a hot path for model authorization checks. The test results show particularly dramatic improvements (3000%+ speedups) for complex patterns with multiple wildcards or special characters, which are common in model naming schemes like "bedrock/", "openai/gpt-", etc.Test Case Performance:
The optimization is most effective when the same wildcard patterns are used multiple times across authorization checks, which is the typical usage pattern in proxy authentication systems.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-is_model_allowed_by_pattern-mhx24r7hand push.