mind1n
mind1n

Reputation: 1206

Is it true that StringBuilder is slower than concatenate a dozen of strings?

Is it true that StringBuilder is slower than concatenate a dozen of strings? How does compiler optimize the string concatenation so that joining a dozen of strings using "+" will be better than StringBuilder?

From a book (written by Ben Watson) it says that:

String Concatenation: For simple concatenation of a known (at compile time) quantity of strings, just use the ‘+’ operator or the String.Concat method. This is usually more efficient than using a StringBuilder. string result = a + b + c + d + e + f; Do not consider StringBuilder until the number of strings is variable and likely larger than a few dozen. The compiler will optimize simple string concatenation in a way to lessen the memory overhead.

Upvotes: 5

Views: 2046

Answers (2)

crumble
crumble

Reputation: 66

Direct concatination needs less objects and memory calls. So it is faster, if you concatinate all strings (with out any text processing) in one statement.

In this case the compiler can calculate the size of the new string and allocate the memory and copy all chars into it. So you create only the object you want.

If you are using the StringBuilder, you use an additional object. If you append long strings without telling the StringBuilder in the constructor to use a huge buffer size, the string builder may do multiple memory allocations and copies, because it may run several times over the standard memory allocations.

StringBuild is the better solution, if you build your string in a loop. In this case the direct concatination will create a new object and memory allocation in each iteration, where StringBuild use only one memory allocation (if you use the right value in the constructor) and only two objects.

But it is hard to tell something about the runtime. The implementation changes over time. So what is now best practice may be worst practice in 5 years.

Upvotes: 1

Asik
Asik

Reputation: 22133

String.Concat is more efficient because it knows all the string lengths from the start. So it can allocate a single buffer with just the right length, copy the strings into it and return that buffer.

StringBuilder has to allocate a small buffer, reallocating and copying everytime a call to Append causes it to run out of space. The final call to ToString() also has to allocate yet another buffer.

So use String.Concat when you know in advance how many strings you have; use StringBuilder when you don't.

In C#, chained calls to the + operator are automatically converted to a single call to String.Concat.

Upvotes: 10

Related Questions