What are the best practices for string concatenation in loops?
4 minbeginner.NETstringStringBuilderperformance
Quick Answer
Because strings are immutable, `+=` concatenation inside a loop allocates a new string (and copies) on every iteration, producing O(n^2) work and heavy GC pressure. Use `StringBuilder` to accumulate efficiently, or `string.Join`/`string.Concat` when you already have the collection. Reserve simple `+` concatenation for a small, fixed number of pieces.
Detailed Answer
String concatenation in loops can severely impact performance because strings are immutable in C#. Each concatenation creates a new string object, leading to excessive memory allocations and garbage collection pressure.
Bad Practice:
string result = "";
for (int i = 0; i < 1000; i++)
{
result += i.ToString(); // Creates 1000 new string objects
}
Best Practices:
- Use StringBuilder for multiple concatenations:
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
sb.Append(i);
}
string result = sb.ToString();
- Pre-allocate capacity when size is known:
var sb = new StringBuilder(capacity: 5000);
for (int i = 0; i < 1000; i++)
{
sb.Append(i);
}
- Use string.Join() for collections:
var numbers = Enumerable.Range(0, 1000);
string result = string.Join(",", numbers);
- Use string interpolation for simple cases:
// For few concatenations (2-3), this is optimized by the compiler
string result = $"{firstName} {lastName}";
Performance Impact:
- String concatenation: O(n²) time complexity
- StringBuilder: O(n) time complexity
- For 1000+ concatenations, StringBuilder is 100-1000x faster