⚡️ Speed up method EventSource._get_charset by 40%
#152
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.
📄 40% (0.40x) speedup for
EventSource._get_charsetinskyvern/client/core/http_sse/_api.py⏱️ Runtime :
721 microseconds→515 microseconds(best of231runs)📝 Explanation and details
The optimization replaces expensive regex operations with faster string operations for the common case. The key changes are:
What was optimized:
content_type.lower().find("charset=")instead of immediately callingre.search()with regex pattern matchingWhy it's faster:
.find()operations are significantly faster than regex compilation and matching (90%+ of execution time was spent in the encode/decode validation, but the regex overhead was still meaningful); \t\r\n) avoids regex overhead for simple parsingPerformance characteristics:
The optimization is especially valuable since this function likely runs on every SSE connection establishment, making even small improvements impactful for high-throughput applications.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-EventSource._get_charset-mjaph18land push.