⚡️ Speed up function string_concat by 30%
#182
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.
📄 30% (0.30x) speedup for
string_concatinsrc/algorithms/string.py⏱️ Runtime :
650 microseconds→500 microseconds(best of250runs)📝 Explanation and details
The optimization replaces string concatenation in a loop with a list comprehension followed by a single join operation, delivering a 29% speedup.
Key Performance Changes:
Eliminated quadratic string concatenation: The original code's
s += str(i)creates a new string object on each iteration since strings are immutable in Python. This results in O(n²) time complexity as each concatenation copies the entire existing string.Replaced with linear list building + join: The optimized version uses
[str(i) for i in range(n)]to build a list of strings in O(n) time, then performs a single''.join(s)operation that efficiently allocates the final string size upfront.Why This Works:
str.join()pre-calculates the total string length and allocates memory once, eliminating the repeated allocations and copying of the original approachPerformance Evidence:
The line profiler shows the optimization particularly benefits larger inputs - the original code spent 54.4% of time in string concatenation operations, while the optimized version completes the entire operation in just 573 nanoseconds vs 5,456 nanoseconds total.
Test Case Effectiveness:
This optimization especially benefits the large-scale test cases (
test_concat_large_n_100,test_concat_large_n_1000) where the quadratic behavior of string concatenation becomes more pronounced. Small inputs (n < 10) see modest gains, but larger inputs will see exponentially better performance.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-string_concat-mivnq2dvand push.