提高字符串生成器的性能

use*_*219 2 .net c#

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);
        }
Run Code Online (Sandbox Code Playgroud)

与使用相比,这提供了约25%的改善,StringBuilder并且因此不太令人满意.

Aak*_*shM 7

如果您事先想到最终字符串的大小(就像您所做的那样),您可以构建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
Run Code Online (Sandbox Code Playgroud)

这可能会有所帮助.