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

懵懂的女人 提交于 2019-12-06 04:13:16

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.

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.

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