Search code examples
c#.netstringstringbuilderstring-building

What problem does the StringBuilder solve?


Why would I use a StringBuilder over simply appending strings? For example why implement like:

StringBuilder sb = new StringBuilder;
sb.Append("A string");
sb.Append("Another string");

over

String first = "A string";
first += "Another string";

?


Solution

  • The documentation of StringBuilder explains its purpose:

    The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.