Think += is efficient? You're rebuilding the entire wall just to add one brick!
By Fuat Can Köseoğlu,
That's right - string concatenation in a loop doesn't just perform poorly, it creates quadratic (O(n²)) growth in both time and memory allocations that can bring your application to its knees. Why String Concatenation has Quadratic Cost? • In C#, strings are immutable. Every time you concatenate two strings, the runtime: • Allocates new memory for the combined length • Copies the first string byte-by-byte into new memory • Copies the second string after it • Returns a new string reference • Marks the old strings for garbage collection This means in a loop that builds a string character by character: • Iteration 1: Creates 1-character string • Iteration 2: Copies 1 char + adds 1 = creates 2-character string (2 allocations total) • Iteration 3: Copies 2 chars + adds 1 = creates 3-character string (3 allocations total) • Iteration N: Copies N-1 chars + adds 1 = creates N-character string • Total allocations for N iterations: 1 + 2 + 3 + ... + N = N(N+1)/2 • For 1000 iterations: 1000 × 1001 ÷ 2 = ~500,000 total character copies across intermediate strings! Note: Although the math shows 500,500 character copies, not every intermediate string creates a separate heap object—GC may optimize some. The core issue is the heavy allocation pressure and quadratic time complexity. StringBuilder maintains: • Internal char[] buffer that grows geometrically (doubles when full) • Current position tracker for next character insertion • Capacity management to minimize buffer reallocations • When you call ToString(), it creates exactly one final string from the buffer. Best Practices: • DO: Use StringBuilder for Dynamic String Building Pre-size with estimated capacity to prevent internal buffer reallocations • DO: Use String.Join() for Known Collections Most efficient for joining known collections with separators • DON'T: Use += in Loops Creates quadratic allocation pressure that kills performance! • DON'T: Create StringBuilder for Few Concatenations Direct concatenation is fine for 2-3 strings - StringBuilder has overhead This is Critical in Unity Game Development: • Poor string concatenation can trigger garbage collection spikes, causing frame drops in your game during: • UI text generation (scores, health displays, tooltips) • Debug logging with formatted messages • Save data serialization (JSON/XML building) • Shader property name building for dynamic materials Follow for O(1) access to daily game dev tips!