⚡️ Speed up function levenshtein_distance by 12% in PR #924 (small-fixes)
#927
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.
⚡️ This pull request contains optimizations for PR #924
If you approve this dependent PR, these changes will be merged into the original PR branch
small-fixes.📄 12% (0.12x) speedup for
levenshtein_distanceincodeflash/discovery/functions_to_optimize.py⏱️ Runtime :
1.91 seconds→1.71 seconds(best of6runs)📝 Explanation and details
The optimized version achieves an 11% speedup through several key memory and algorithmic optimizations:
Primary Optimizations:
Pre-allocated buffer reuse: Instead of creating a new
newDistanceslist on every iteration (16,721 allocations in the profiler), the optimized version uses two pre-allocated lists (previousandcurrent) that are swapped via reference assignment. This eliminates ~16K list allocations per call.Eliminated tuple construction in min(): The original code creates a 3-element tuple for
min((a, b, c))8+ million times. The optimized version uses inline comparisons (a if a < b else b), avoiding tuple overhead entirely.Direct indexing over enumerate: Replaced
enumerate(s1)andenumerate(s2)withrange(len1)and direct indexing, eliminating tuple unpacking overhead in the inner loops.Cached string lengths: Pre-computing
len1andlen2avoids repeatedlen()calls.Performance Impact by Test Case:
Context Impact:
The function is used in
closest_matching_file_function_name()for fuzzy matching function names. Since this involves comparing many short-to-medium function names, the optimization should provide measurable benefits in code discovery workflows where hundreds of function name comparisons occur.The optimization is most effective for the common case of comparing function names (typically 5-20 characters), where memory allocation savings outweigh setup costs.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-pr924-2025-11-17T17.24.40and push.