⚡️ Speed up function regex_match by 124%
#183
Closed
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.
📄 124% (1.24x) speedup for
regex_matchinsrc/algorithms/string.py⏱️ Runtime :
3.87 milliseconds→1.73 milliseconds(best of250runs)📝 Explanation and details
The optimization improves performance by pre-compiling the regex pattern once instead of compiling it on every iteration.
Key Change: Added
regex = re.compile(pattern)before the loop and usedregex.match(s)instead ofre.match(pattern, s).Why This is Faster: In the original code,
re.match(pattern, s)internally compiles the pattern string into a regex object on every call. With thousands of strings to process, this compilation overhead becomes significant. The line profiler shows the originalre.match(pattern, s)line took 83.4% of total runtime (34.9ms out of 41.9ms), while the optimized version reduces this to just 22% (5.4ms out of 24.7ms).Performance Impact: The optimization delivers a 123% speedup (from 3.87ms to 1.73ms) because:
Test Case Performance: The optimization particularly excels in:
This optimization is especially valuable when the function processes large datasets or is called frequently, as the compilation savings compound with input size.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
To edit these changes
git checkout codeflash/optimize-regex_match-mivnsmwnand push.