2

I tested a simple concatenation:

 string res = "";
 for (var i = 0; i < 1000; i++)
 {
     res += mystring;     
 }
 return res;

and another with a StringBuilder object:

 StringBuilder builder = new StringBuilder();
 for (var i = 0; i < 1000; i++)
 {
     builder.Append(mystring);           
 }
 return builder.ToString();

The bigger is the cycle, the better are the performances using the StringBuilder.

I would like to know the real reason of this result, I mean, that fact of creating, implementing an object, calling methods is faster than a simple string1 + string2?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Matteo Gariglio
  • 482
  • 5
  • 12
  • 2
    Read Jon Skeet's [Concatenating Strings Efficiently](http://yoda.arachsys.com/csharp/stringbuilder.html) – dcastro Jul 12 '14 at 19:30

1 Answers1

6

Strings are immutable, so each += mystring creates a new object. In the StringBuilder case you're operating on one instance, hence the performance difference. You can improve the performance further by configuring the Capacity property. You can find more information on this issue in the documentation.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130