Course contentsShow
← Computer Science
Lesson 269 of 2,8726. Arrays and Basic CollectionsFree lesson

String Building and Concatenation Efficiency

Understanding performance implications of string concatenation and using mutable character buffers for efficient string construction.

String Building and Concatenation Efficiency

What you'll learn: Why repeatedly gluing strings together can slow your program down, and how to build strings efficiently instead.

The Hidden Cost of String Concatenation

Remember that strings are often immutable (unchangeable). When you concatenate strings like result = str1 + str2, your program doesn't just append characters to the end. Instead, it:

  1. Allocates memory for a brand new string
  2. Copies all characters from str1
  3. Copies all characters from str2
  4. Discards the old strings

This works fine once or twice. But imagine building a string in a loop:

result = ""
for i in range(1000):
    result = result + "X"  // Creates a NEW string each time!

On iteration 1, you copy 1 character. Iteration 2: copy 2 characters. Iteration 1000: copy 1000 characters. That's roughly 500,000 character copies for just 1000 additions!

The Solution: Mutable Character Buffers

Think of immutable strings like writing in permanent marker—you can't change what's written, only create a new page. A mutable character buffer is like a whiteboard where you can erase and add without starting over.

Many languages provide specialized structures (like StringBuilder or character arrays) that:

  • Reserve extra space in memory upfront
  • Let you append characters without copying everything
  • Convert to a final immutable string only when finished

This transforms our 500,000 operations into roughly 1000—a massive speedup!

When It Matters

For a few concatenations, the simple approach is fine. But when building strings in loops or processing large text, using a mutable buffer can mean the difference between instant results and a frozen program.

Key Takeaway: Repeatedly concatenating immutable strings copies all data every time—extremely slow in loops. Use mutable character buffers for efficient string building when performance matters.