StringBuilder and '+' operator

.net, c#, compiler-optimization

Solution

I agree with all the answers, but to me you need to understand strings in C# and they way they are actually manipulated 'under the covers'

The use of a StringBuilder comes in to its own when 5 or more strings are being concatenated. This is because the compiler intrinsically converts:

string a = b + c + d + e + f;

into

r = String.Concat(new String[5] { a, b, c, d, e });

so there is an implicit overhead of array creation.

I would suggest reading the following by Eric Lippert who wrote string concatenation in C#: http://ericlippert.com/2013/06/17/string-concatenation-behind-the-scenes-part-one/ http://ericlippert.com/2013/06/24/string-concatenation-behind-the-scenes-part-two/

Problem

Im maintaining thise code here which often has a pattern like the following: ``` StringBuilder result = new StringBuilder(); result.Append("{=" + field.Name + "={"); ``` It seems like a waste with a lot of useless object construction when doing it like this and I want to rewrite to this: ``` result.Append("{=").Append(field.Name).Append("={"); ``` Is it correct that the first version is putting more strain on the GC? Or is there some optimization in the C# compiler with string literals where concatenating string's with string literals does not create temporary objects?

Original source

Related problems