大量的 StringBuilder.Append()
操作是否可以通过使用分配在线程堆栈上的 char[]
来优化,以使用指针按字符构建字符串?
unsafe
{
const Int32 width = 1024;
Char* msg = stackalloc Char[width];
Int32 index = 0;
property = Environment.MachineName;
for (Int32 i = 0; i < property.Length; i++)
msg[index++] = property[i];
return new String(msg, 0, width);
}
与使用 StringBuilder
相比,这提供了大约 25% 的改进,结果并不十分令人满意。
最佳答案
如果你预先知道你的最终字符串有多大(就像你看起来的那样),你可以构建具有该容量的 StringBuilder
开始,所以它花费更少的时间重新分配空间:
var sb = new StringBuilder();
// capacity 16, will expand as needed
var sb30000 = new StringBuilder(30000);
// capacity 30000, will not need to expand until that length is passed
这可能有点帮助。
关于c# - 提高字符串生成器的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11133973/