⚡️ Speed up function reverseString by 6,536%
#1069
Open
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,536% (65.36x) speedup for
reverseStringincode_to_optimize_js/string_utils.js⏱️ Runtime :
14.3 milliseconds→215 microseconds(best of1runs)📝 Explanation and details
The optimized code achieves a 65x speedup (6536%) by eliminating quadratic time complexity.
Key Changes:
Algorithmic improvement: O(n²) → O(n)
Memory allocation reduction
join('').Why This Leads to Speedup:
In JavaScript, strings are immutable. The original code's
temp += result[j]pattern forces the JavaScript engine to:With a 1000-character string, this means ~500,000 character copies and ~1000 allocations. The optimized version does exactly 1000 character assignments into a pre-sized array, then one join operation—dramatically reducing memory churn and CPU cycles.
Test Case Performance:
The optimization excels across all test sizes:
The performance tests with 1000+ characters specifically validate this—the original's 14.3ms vs optimized's 215μs demonstrates the practical impact of eliminating the O(n²) bottleneck.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-reverseString-mkgdzag9and push.