Strings
Loading
Loading
Strings
Why building a string in a loop can be quadratic, and what to do instead.
By the end of this chapter
In most languages a string cannot be modified after it is created. Concatenation therefore allocates a new string and copies both operands into it.
# Quadratic: each += copies everything accumulated so fardef build_slow(chars): out = "" for char in chars: out += char # allocates a new string every iteration return out # Linear: collect the pieces, join oncedef build(chars): pieces = [] for char in chars: pieces.append(char) return "".join(pieces)| Language | Buffer to use |
|---|---|
| Python | a list plus "".join(...) |
| Java | StringBuilder |
| C++ | std::string with += (already amortised) |
| JavaScript | an array plus .join("") |
| Operation | Time | Space |
|---|---|---|
| Read character at index | O(1) | O(1) |
| Length | O(1) | O(1) |
| Concatenate | O(n + m) | O(n + m) |
| Substring / slicecopies in most languages | O(k) | O(k) |
| Search for a substring | O(n · m) naive | O(1) |
Quick quiz
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for:
Before moving on: take the quiz above.