Why a Tiny Addition Can Become Expensive

A string is a sequence of characters, but in many languages it is immutable: once created, its contents cannot be changed in place. An expression such as `text = text + "a"` may look like it adds one character to an existing string. Instead, the program can allocate a new string, copy the old contents into it, and append the character. The original string is left behind to be reclaimed later.

The Cost Compounds

The first addition copies one character; the next may copy two; the one after that, three. After a million additions, the program may have copied roughly the sum of all those growing lengths—not merely a million characters. That makes the work grow approximately with the square of the final string length, a pattern called quadratic time.

The practical consequence is that a loop that seems to do one small operation each time can slow sharply as the result grows. It can also create many temporary strings, increasing memory use and the work required to clean them up.

Build Once, Then Convert

A common fix is a mutable builder, such as a string buffer or list of pieces. It stores additions without copying the entire accumulated result each time, then combines them into one string at the end. Some languages also optimize particular concatenation patterns, so the exact cost depends on the language and how the code is written. But when repeated growth is the bottleneck, avoiding a fresh full-string copy on every iteration can turn a painfully growing task into a roughly linear one.