Question

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

?

Was it helpful?

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.

OTHER TIPS

In a simple case like yours, it really doesn't matter. But generally, strings are immutable, that means every change to a string variable will create a new buffer in memory, copy the new data and abandon the old buffer. In case you are doing a lot of string manipulation, this slows down your program and leads to a lot of abandoned string buffers, that need to be collected by the garbage collector.

Basically string immutability problems. Also it provides methods for simpler manipulation of string. Take a look at Using Stringbuilder Class

StringBuilder is mutable. Strings are not. So any operation on a string creates a new object. In your 2nd sample, 2 objects are created (one on each line). Whereas in the first, only one object is created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top