4

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

?

m.edmondson
  • 30,382
  • 27
  • 123
  • 206
  • 1
    See http://www.yoda.arachsys.com/csharp/stringbuilder.html – Jon Skeet Mar 31 '11 at 11:12
  • It's a really memory efficient (with performance benefits) way of appending a large number of strings together without costing that many objects. (less objects ~ less time required by garbage collector) – st0le Mar 31 '11 at 11:13
  • 3
    Outside a loop it's not a big deal as the compiler will probably optimise that to `String first = "A stringAnother string";` one string. Everyone else seems to have covered the reasons not to use it in a loop. – BenCr Mar 31 '11 at 11:15

4 Answers4

10

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
5

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.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

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

archil
  • 39,013
  • 7
  • 65
  • 82
0

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.

Tundey
  • 2,926
  • 1
  • 23
  • 27
  • 2
    That's right. But in reality if you don't need to do lots of string operations, String and StringBuilder performs almost equally, and in case of short strings and few appends, simple string works better. – Dmitry Karpezo Mar 31 '11 at 12:01