⚡️ Speed up function merge_multi_strings by 6%
#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.
📄 6% (0.06x) speedup for
merge_multi_stringsindoctr/models/recognition/utils.py⏱️ Runtime :
7.28 milliseconds→6.88 milliseconds(best of241runs)📝 Explanation and details
The optimized code achieves a 5% speedup by eliminating redundant computations and reducing memory allocations in the
merge_stringsfunction:Key Optimizations:
Single-pass score computation: Instead of creating the
scoreslist in one pass and then creatingzero_matchesin a separate enumeration, the optimized version combines both operations in a single loop. This eliminates the need to iterate throughscorestwice.Precomputed expected_overlap: Moved the calculation of
expected_overlapoutside of conditional branches to avoid redundant computation on every path.In-place minimum finding: Replaced
combined_scores.index(min(combined_scores))with a manual loop that finds the minimum without creating an intermediate list. This eliminates the memory allocation forcombined_scoresand avoids a second pass through the data.Reduced list comprehension overhead: The combined loop approach avoids the overhead of multiple list comprehensions and their associated memory allocations.
Performance Benefits:
The optimizations are particularly effective for the common use cases shown in tests, where strings have partial overlaps and the function needs to compute Hamming distances across multiple potential alignment positions.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
common/test_models_recognition_utils.py::test_merge_multi_strings🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-merge_multi_strings-mg7io5aqand push.