Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";

?

like image 398
m.edmondson Avatar asked Dec 07 '22 22:12

m.edmondson


1 Answers

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.

like image 89
David Heffernan Avatar answered Jan 04 '23 02:01

David Heffernan