⚡️ Speed up function split_sentence_str
by 135%
#69
+2
−2
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.
📄 135% (1.35x) speedup for
split_sentence_str
inguardrails/validator_base.py
⏱️ Runtime :
196 microseconds
→83.6 microseconds
(best of63
runs)📝 Explanation and details
The optimization replaces the inefficient
split()
andjoin()
operations with direct string slicing usingfind()
.Key changes:
split(".")
: The original code splits the entire string into fragments, creating a list of all substringsjoin()
: The original code reconstructs the second part by joining all fragments after the firstchunk.find(".")
to locate the first period, then slices the string at that positionWhy this is faster:
split()
processes the entire string and creates multiple substring objects, even though we only need the position of the first periodjoin()
concatenates all remaining fragments with periods, creating unnecessary string operationsfind()
+ slicing performs only one pass through the string until the first period is found, then creates exactly two substringsPerformance gains by test case:
find()
stops at the first period rather than processing the entire stringThe optimization is most effective when strings contain multiple periods or are long, but provides consistent improvements across all test cases.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-split_sentence_str-mh2n5x5w
and push.