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

断了今生、忘了曾经 提交于 2019-12-07 20:38:36

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/46151516/is-it-true-that-stringbuilder-is-slower-than-concatenate-a-dozen-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!