Back to results for “Objects”
C# Programming › Strings in C#

What is the difference between System.Text.StringBuilder and System.String?

Intermediate

Answer

System.String is immutable, meaning every modification creates a brand new string object in memory, which can become inefficient when you need to build up or modify text repeatedly, such as inside a loop. System.Text.StringBuilder, on the other hand, is a mutable class specifically designed for efficiently building and modifying text, since it can append, insert, or remove characters directly within its internal buffer without creating a new object every single time, making it significantly faster for heavy string manipulation scenarios.
var sb = new System.Text.StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.Append("Line " + i + "\n");
}
string result = sb.ToString();
Real-world example A log file generator that writes thousands of lines uses StringBuilder to efficiently assemble the entire log content in memory before writing it to disk once, avoiding the performance cost of creating a new string object for every single line.

Common follow-ups: When is it acceptable to use string concatenation instead of StringBuilder?;How does StringBuilder manage its internal memory buffer?