⚡️ Speed up method BrotliMiddleware._is_compressible_file_type by 33%
#62
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.
📄 33% (0.33x) speedup for
BrotliMiddleware._is_compressible_file_typeingradio/brotli_middleware.py⏱️ Runtime :
2.10 milliseconds→1.58 milliseconds(best of19runs)📝 Explanation and details
The optimization achieves a 33% speedup through two key changes that eliminate redundant operations in the hot path:
1. Move set creation to initialization: The original code recreated the
compressible_extensionsset on every method call (line profiler shows 21.5% of time spent here). The optimized version moves this to__init__, converting it from a per-call allocation to a one-time instance variable. This eliminates thousands of set creations when the method is called frequently.2. Replace
split()withrpartition(): The original code usedpath.split(".")[-1]which creates an entire list of all path segments, then discards everything except the last element. The optimized version usespath.rpartition(".")[-1]which directly finds the last dot and returns only the final segment without creating intermediate data structures.Performance impact by test type:
Why this matters: The
_is_compressible_file_typemethod is called in the middleware's__call__method for every HTTP request to determine if response compression should be applied. In web applications serving many static assets (HTML, CSS, JS, JSON), this method executes thousands of times per second. The eliminated allocations reduce both CPU cycles and garbage collection pressure, making the middleware more efficient under load.The optimization maintains identical behavior while removing computational waste from the request processing pipeline.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-BrotliMiddleware._is_compressible_file_type-mhwqj1maand push.