⚡️ Speed up function _get_response_headers by 12%
          #166
        
          
      
  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.
  
    
  
    
📄 12% (0.12x) speedup for
_get_response_headersinlitellm/litellm_core_utils/exception_mapping_utils.py⏱️ Runtime :
45.6 microseconds→40.5 microseconds(best of72runs)📝 Explanation and details
The optimized code achieves a 12% speedup through strategic restructuring and early returns that reduce unnecessary attribute lookups and assignments.
Key optimizations:
Early return pattern: Instead of always assigning to
_response_headersand checking it later, the code now returns immediately whenerror_response.headersis found, eliminating subsequent unnecessary checks and assignments.Reduced redundant operations: The original code performed multiple conditional checks on
_response_headerseven after finding headers. The optimized version uses early returns to skip these redundant operations.Streamlined control flow: By restructuring the nested conditions and eliminating the intermediate variable assignment for
error_response.headers, the code path is more direct when headers are found in the response object.Performance impact by test case type:
response.headersbenefit most from the early return pattern, avoiding the finallitellm_response_headerslookupheadersattributes benefit from reduced variable assignmentslitellm_response_headerssee smaller gains since they still need to traverse the full logic pathThe optimization maintains identical functionality while reducing the average number of operations per call, particularly benefiting the common case where headers are found in the response object.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_response_headers-mhdl0gzcand push.