Concatenating .NET String (+ & + =) vs StringBuilder

I am reading a book called .NET Gotchas (well worth reading IMO), which illustrates the performance differences between String and StringBuilder, and this raised a question that I felt could not go unanswered! Although I do not know the internal components of any class (without looking at the reflected versions of these classes), I was interested; since the operators in .NET are overloaded, why didn’t Microsoft implement the String class to use StringBuilder internally and overload the concatenation operators to just call .Append () on the StringBuilder? I suppose there are some fundamental reasons why this is not so, and if so, why?

+5
source share
2 answers

The problem is not so much that string concatenation is slow, but that repeated concatenation creates a lot of intermediate lines that need to be allocated and garbage collected later.

EDIT
Note that it mystring += "a"doesn’t just add β€œa” to the previous line. He creates a new line for the combination and points to it "mystring", thereby discarding the previous value (if there are no more links on it).

End edit

Row

string mystring = "something";
mystring += "something else";
mystring = mystring + "third";

will work slower if you execute each individual line as adding StringBuilder and then .ToString () to return the result to the string. You will only get performance gains if you use one StringBuilder, Append () for it several times and do .ToString () at the very end.

StringBuilder sb = new StringBuilder();
sb.Append("something");
sb.Append("something else");
sb.Append("third");
string mystring = sb.ToString();

StringBuilder , , .

, :

string mystring = "something" + "something else" + "third";

.

+6

:

string result = a + b;

,

var sb = new StringBuilder(a, a.Length + b.Length);
sb.Append(b);
string result = sb.ToString();

StringBuilder , , .

+5

All Articles