⚡️ Speed up function calculate_edit_distance by 150%
#269
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.
📄 150% (1.50x) speedup for
calculate_edit_distanceinunstructured/metrics/text_extraction.py⏱️ Runtime :
5.47 milliseconds→2.19 milliseconds(best of60runs)📝 Explanation and details
The optimized code achieves a 150% speedup (from 5.47ms to 2.19ms) by eliminating redundant dictionary construction and replacing inefficient character-by-character replacements with a pre-computed translation table.
Key Optimizations
1. Module-level Pre-computation
The original code reconstructed the
double_quotesandsingle_quotesdictionaries on every call tostandardize_quotes(217 calls in the profile). This consumed ~23% of runtime just building dictionaries. The optimized version moves these to module-level constants (_DOUBLE_QUOTES,_SINGLE_QUOTES), computed once at import time.2. Translation Table (
str.translate())The original code used a loop with
unicode_to_char()conversions and individualstr.replace()calls for each quote type (~40 iterations per call). The optimized version pre-computes all unicode characters and builds a single translation table (_QUOTE_TRANSLATION) usingstr.maketrans(). This allowsstr.translate()to replace all quote characters in a single pass through the string, which is implemented in C and far more efficient than Python loops with multiplereplace()calls.Line profiler shows
standardize_quotesdropped from 25.9ms total time (with ~65% spent in loops and dictionary construction) to just 0.5ms (single translate call).3. Faster Validation Check
Changed
return_as not in return_typesfrom a list lookup to a tuple literal checkreturn_as not in ("score", "distance"). This avoids list construction on every call and uses Python's optimized tuple comparison. The list is now only created in the error path (3 out of 105 calls).Impact on Workloads
The
function_referencesshowcalculate_edit_distanceis called bycalculate_accuracy, which appears to be a high-level metric function. Given that the test results show 3-10x speedups on individual calls (e.g., 44μs → 9μs for typical inputs), any workflow processing multiple documents or computing accuracy metrics repeatedly will benefit significantly. The optimization is particularly effective when:translate()scales better than multiplereplace()operations (e.g., 500-char strings show 272% speedup)Test cases with standard ASCII text show ~380% speedup, while those with unicode quotes show ~330% speedup - demonstrating consistent gains across input types. The optimization maintains correctness while reducing overhead from 94% of runtime to negligible levels.
✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
metrics/test_text_extraction.py::test_calculate_edit_distancemetrics/test_text_extraction.py::test_calculate_edit_distance_with_filenamemetrics/test_text_extraction.py::test_calculate_edit_distance_with_various_whitespace_1metrics/test_text_extraction.py::test_calculate_edit_distance_with_various_whitespace_2🌀 Click to see Generated Regression Tests
🔎 Click to see Concolic Coverage Tests
codeflash_concolic_xdo_puqm/tmpnhjwc_rx/test_concolic_coverage.py::test_calculate_edit_distancecodeflash_concolic_xdo_puqm/tmpnhjwc_rx/test_concolic_coverage.py::test_calculate_edit_distance_2codeflash_concolic_xdo_puqm/tmpnhjwc_rx/test_concolic_coverage.py::test_calculate_edit_distance_3To edit these changes
git checkout codeflash/optimize-calculate_edit_distance-mks22n2zand push.