Sub topic 6
Building strings without quadratic cost
This chapter assumes you know loops, lists, and basic Big-O notation. It also assumes you know that strings are immutable, meaning an existing string cannot be changed in place. The previous chapter covered why. Here we look at what that costs when you build a large string, and how to avoid the cost.
Why concatenation can be quadratic
Because a string cannot be changed, a + b has to produce a new string. The runtime allocates room for len(a) + len(b) characters. It then copies both inputs into that space.
Now put that inside a loop. Suppose you append one character per step to build a string of length n:
- Step 1 copies 1 character.
- Step 2 copies 2 characters.
- Step 3 copies 3 characters.
- Step n copies n characters.
The total is 1 + 2 + ... + n, which is n(n+1)/2 copies. That is O(n²). Doubling the input roughly quadruples the work.
The CPython caveat
The CPython runtime has an optimization. When a string has only one reference, result += p can sometimes resize the string in place. That makes the loop look linear in simple tests.
Do not rely on this. It is an implementation detail. It does not apply in other Python implementations, and it can fail when another variable also refers to the string. Java and JavaScript make no such promise in general. Write code that is linear by design.
The fix: collect pieces, then join once
Store the pieces in a list. Then call join one time at the end. Appending to a list is amortized O(1). join first adds up the lengths of all pieces and allocates the result once. It then copies each piece exactly once. The total is O(n).
parts = [str(i) for i in range(5)]
# Repeated concatenation may copy the growing string on each step
result = ""
for p in parts:
result += p
# join computes the total size once and copies each piece once
result_joined = "".join(parts)
print(result == result_joined) # True
print(result_joined) # 01234Both versions give the same answer. Only the cost differs.
Measuring the difference
Do not guess. Time both approaches on a large input.
import time
def concat(n):
s = ""
for i in range(n):
s += "x"
return s
def joined(n):
parts = []
for i in range(n):
parts.append("x")
return "".join(parts)
for n in (100_000, 200_000, 400_000):
t0 = time.perf_counter()
concat(n)
t1 = time.perf_counter()
joined(n)
t2 = time.perf_counter()
print(n, round(t1 - t0, 4), round(t2 - t1, 4))On CPython the concat times may look nearly linear because of the optimization above. The point is that joined is linear everywhere, while concat is only linear when the runtime helps.
The same idea in other languages
Most languages offer a mutable buffer built for this job.
| Language | Tool for building strings |
|---|---|
| Python | list of pieces and `"".join(...)` |
| Java | `StringBuilder` |
| JavaScript | array and `join`, or `+=` (engines optimize it with ropes) |
| Go | `strings.Builder` |
| C# | `StringBuilder` |
A builder keeps a growable array of characters. Appending usually writes into spare capacity. When the capacity runs out, the builder allocates a larger array, often twice the size, and copies once. Doubling makes the copies add up to O(n) overall. Call toString (or the equivalent) at the end to get an immutable string.
A rope is another design. It stores a tree of string fragments, so joining two strings is cheap. The cost moves to indexing and to flattening the tree later.
Common errors
- Using
+=on a string inside a loop that runs many times. - Calling
joininside the loop, which rebuilds the string on each step and loses the benefit. - Building a list of non-strings, then calling
join. In Python,"".join([1, 2])raises aTypeError. Convert withstr()first. - Using
joinfor two or three pieces. Plain+or an f-string is clearer and just as fast at that size.
Exercise
A loop appends 1 character to a string 50,000 times with s += c on a runtime that does not optimize this. Roughly how many characters are copied in total, and what change makes the cost linear?
Show answer
About n(n+1)/2 = 50,000 × 50,001 / 2, which is roughly 1.25 billion character copies. Append each character to a list (or a builder) and call "".join(parts) once after the loop. That copies each character once, so the work is about 50,000 copies.
Exercise
Why does a builder that doubles its capacity give O(n) total copy cost for n appends?
Show answer
A resize at capacity c copies c characters. Resizes happen at capacities 1, 2, 4, 8, and so on up to about n. These copies sum to less than 2n, so the total copying is O(n) and each append is O(1) amortized.