StringBuilder 真的比连接十几个字符串慢吗? [英] Is it true that StringBuilder is slower than concatenate a dozen of strings?

查看:32
本文介绍了StringBuilder 真的比连接十几个字符串慢吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

StringBuilder 真的比连接十几个字符串还慢吗?编译器如何优化字符串拼接,使得使用+"连接十几个字符串会比StringBuilder更好?

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?

从一本书(由 Ben Watson 撰写)中说:

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

String Concatenation:用于简单的已知字符串的连接(在编译时time) 字符串的数量,只需使用+"运算符或String.Concat 方法.这通常比使用字符串生成器.字符串结果 = a + b + c + d + e + f;不要考虑 StringBuilder 直到字符串的数量是可变的并且可能大于几十个.编译器将优化简单以减少内存开销的方式进行字符串连接.

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.

推荐答案

String.Concat 效率更高,因为它从一开始就知道所有字符串长度.因此它可以分配一个长度合适的缓冲区,将字符串复制到其中并返回该缓冲区.

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 必须分配一个小缓冲区,每次调用 Append 时都会重新分配和复制导致空间不足.对 ToString() 的最后调用还必须分配另一个缓冲区.

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.

所以当你事先知道你有多少个字符串时,使用String.Concat;不使用时使用 StringBuilder.

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

在 C# 中,对 + 运算符的链式调用会自动转换为对 String.Concat 的单个调用.

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

这篇关于StringBuilder 真的比连接十几个字符串慢吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆