Question: How can I efficiently append one string to another in Python? Is there a faster alternative to the following code?
<code class="python">var1 = "foo" var2 = "bar" var3 = var1 + var2</code>
Answer:
CPython, the main Python implementation, now optimizes string concatenation by attempting to extend the string in place when only one reference to a string is present. This optimization results in amortized O(n) time complexity.
For instance, the following code:
<code class="python">s = "" for i in range(n): s += str(i)</code>
which used to have a time complexity of O(n^2), is now O(n).
Technical Details:
In the CPython implementation, the _PyBytes_Resize function is responsible for this optimization. It allows the resizing of strings without creating a new object, provided that only one module references the original string.
Performance Analysis:
Empirical testing demonstrates the significant performance improvement for string concatenation operations:
String Size | Concatenation Time (CPython) |
---|---|
10 | 1.85 usec |
100 | 16.8 usec |
1,000 | 158 usec |
10,000 | 1.71 msec |
100,000 | 14.6 msec |
1,000,000 | 173 msec |
Important Note:
This optimization is specific to CPython and may not be present in other Python implementations, such as PyPy or Jython. In these cases, string concatenation performance may differ from the CPython implementation.
The above is the detailed content of String Concatenation in Python: Is There a Faster Way to Append Strings?. For more information, please follow other related articles on the PHP Chinese website!