⚡️ Speed up method GZipMiddleware.__call__ by 9%
          #18
        
          
      
  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.
  
    
  
    
📄 9% (0.09x) speedup for
GZipMiddleware.__call__instarlette/middleware/gzip.py⏱️ Runtime :
6.18 milliseconds→5.67 milliseconds(best of239runs)📝 Explanation and details
The optimization eliminates the overhead of creating a
Headersobject for every HTTP request by directly accessing the raw header data from the ASGI scope.Key Performance Changes:
Removed Headers Object Creation: The original code creates
Headers(scope=scope)which involves parsing and processing all headers into a dictionary-like structure. The optimized version directly accessesscope.get("headers")which is already a list of(bytes, bytes)tuples.Direct Byte String Operations: Instead of converting headers to strings and using
headers.get("Accept-Encoding", ""), the optimization searches forb"accept-encoding"directly in the byte tuples and checks forb"gzip"substring, avoiding string conversions entirely.Early Loop Termination: The header search stops immediately after finding the
accept-encodingheader with abreakstatement, rather than processing all headers through theHeaderswrapper.Why This is Faster:
Performance Context:
The line profiler shows the
Headers(scope=scope)line took 5.6% of total execution time in the original version, which is completely eliminated. The optimization is particularly effective for high-throughput web applications where this middleware processes many requests per second, as evidenced by the 2.1% throughput improvement (142,506 → 145,551 operations/second) and 9% runtime reduction.This optimization works well across all test scenarios - whether headers contain gzip encoding, use different encodings, or are missing entirely.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-GZipMiddleware.__call__-mhc9anynand push.