Can extensive StringBuilder.Append() operations be optimized by using char[] allocated on thread’s stack to build the string by character using pointers?
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);
}
This gives about 25% improvement compared to using StringBuilder and not quite satisfying as a result.
If you have an idea up front about how big your final string is going to be (as it seems you do), you can construct the
StringBuilderwith that capacity to start with, so it spends less time reallocating space:which might help a bit.