Reputation: 43
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.
Upvotes: 2
Views: 297
Reputation: 63378
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 StringBuilder
with that capacity to start with, so it spends less time reallocating space:
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
which might help a bit.
Upvotes: 7