⚡️ Speed up function _make_span_response_attributes by 340%
#1
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.
📄 340% (3.40x) speedup for
_make_span_response_attributesinsrc/xai_sdk/image.py⏱️ Runtime :
8.43 milliseconds→1.91 milliseconds(best of190runs)📝 Explanation and details
The optimized code achieves a 340% speedup by eliminating redundant operations inside the loop and reducing the number of conditional branches executed.
Key optimizations:
Precomputed format string: The expensive
image_pb2.ImageFormat.Name(request.format).removeprefix("IMG_FORMAT_").lower()operation is moved outside the loop and computed once, rather than being called repeatedly during dictionary initialization.Hoisted conditional logic: Instead of checking
request.formaton every loop iteration (which was the biggest bottleneck at 48% + 24.3% = 72.3% of original runtime), the format check is moved outside the loop. This creates separate optimized loops for each format type.Cached attribute access:
request.formatis stored in a local variablereq_formatto avoid repeated attribute lookups.Performance impact by test case:
The optimization is most effective for workloads with many responses, where eliminating the repeated conditional checks and format string computation provides substantial performance benefits.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_make_span_response_attributes-mgu0bgavand push.