⚡️ Speed up function get_error_message_str by 62%
#101
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.
📄 62% (0.62x) speedup for
get_error_message_strinlitellm/proxy/utils.py⏱️ Runtime :
524 microseconds→324 microseconds(best of218runs)📝 Explanation and details
The optimized code achieves a 61% speedup through two key optimizations:
1. Early Returns Eliminate Redundant Operations
The original code assigns values to
error_messageand then returns it at the end, requiring the function to continue executing through all remaining lines. The optimized version uses directreturnstatements, immediately exiting the function once a condition is met. This eliminates unnecessary variable assignments and subsequent line executions.2. Cached Attribute Access
The original code accesses
e.detailmultiple times in the isinstance checks (isinstance(e.detail, str),isinstance(e.detail, dict)). The optimized version caches this withdetail = e.detailand reuses the cached value, reducing attribute lookup overhead.Performance Impact by Test Case:
json.dumps()completesThe optimizations are particularly effective for the most common paths (string details, dict details) and scale well with data size, as seen in the large-scale test cases where the benefits of early returns are most pronounced.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-get_error_message_str-mhbo48eoand push.