We have a few operations where we are doing a large number of large string concatenations, and have recently encountered an out of memory exception. Unfortunately, debuggin
Here is a nice study about String Concatenation vs Memory Allocation.
If you can avoid concatenating, do it!
This is a no brainer, if you don't have to concatenate but want your source code to look nice, use the first method. It will get optimized as if it was a single string.
Don't use += concatenating ever. Too much changes are taking place behind the scene, which aren't obvious from my code in the first place. I advise to rather use String.Concat() explicitly with any overload (2 strings, 3 strings, string array). This will clearly show what your code does without any surprises, while allowing yourself to keep a check on the efficiency.
Try to estimate the target size of a StringBuilder.
The more accurate you can estimate the needed size, the less temporary strings the StringBuilder will have to create to increase its internal buffer.
Do not use any Format() methods when performance is an issue.
Too much overhead is involved in parsing the format, when you could construct an array out of pieces when all you are using are {x} replaces. Format() is good for readability, but one of the things to go when you are squeezing all possible performance out of your application.