📝 String += Creates New Strings Every Time
Strings are immutable. StringBuilder is mutable. Faster concatenation, less memory. Essential for loops.
❌ String Concatenation (Slow)
string result = " ";
for (int i = 0; i < 10000; i++)
{
result += i.ToString(); // New string each time!
}
✅ StringBuilder (Fast)
var sb = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
sb.Append(i);
}
string result = sb.ToString();
🎯 StringBuilder Methods
var sb = new StringBuilder();
// Append
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
// AppendLine (adds newline)
sb.AppendLine("Hello");
sb.AppendLine("World");
// AppendFormat
sb.AppendFormat("Hello {0}, you are {1} years old", name, age);
// Insert
sb.Insert(0, "Start: ");
// Replace
sb.Replace("World", "Universe");
// Remove
sb.Remove(0, 5);
// Clear
sb.Clear();
// Capacity
sb.Capacity = 1000;
// Length
int length = sb.Length;
💡 Performance Tips
- Use StringBuilder for 10+ concatenations
- Set initial capacity to avoid reallocation
- String.Concat is optimized for small number of strings
- String interpolation is preferred for simple strings
"Building HTML string with += took 5 seconds. StringBuilder took 0.1 seconds. 50x faster. Essential for performance."
