⚡️ Speed up method BrotliMiddleware._is_handler_excluded by 47%
#61
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.
📄 47% (0.47x) speedup for
BrotliMiddleware._is_handler_excludedingradio/brotli_middleware.py⏱️ Runtime :
348 microseconds→238 microseconds(best of41runs)📝 Explanation and details
The optimization improves the
_is_handler_excludedmethod by replacing theany()generator expression with an explicit early-return loop structure and adding a short-circuit check for empty excluded handlers.Key optimizations applied:
Early return for empty handlers: Added
if not self.excluded_handlers: return Falseto immediately return when no patterns exist, avoiding unnecessary iteration setup.Explicit loop with early termination: Replaced
any(pattern.search(handler) for pattern in self.excluded_handlers)with a direct for-loop that returnsTrueimmediately upon finding the first match, eliminating the generator overhead and function call overhead ofany().Why this is faster:
any()function with a generator expression creates additional Python object overhead for each iteration, while the explicit loop operates directly on the iterable.any()adds an extra function call layer that's eliminated in the optimized version.excluded_handlersis empty (common case), the optimization immediately returns without any iteration setup.Performance impact based on test results:
The optimization is particularly valuable since
_is_handler_excludedis called for every HTTP request in the ASGI middleware pipeline, making even small per-call improvements significant for high-traffic applications.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-BrotliMiddleware._is_handler_excluded-mhwqarciand push.