2

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.

3
  • 2
    @Nuffin Umm, perhaps the very first line? Just needs a question mark. However, the question seems at odds with the second line, perhaps the OP wants a code review instead. Commented Jun 21, 2012 at 8:09
  • 6
    Have you experimentally measured that using StringBuilder.Append is a bottleneck for your application and you really need to descend to the pointer and unsafe code level? Or are you just prematurely attempting to save a couple of CPU cycles without a solid reason? Commented Jun 21, 2012 at 8:12
  • 3
    A StringBuilder can have an initial capacity which probably would give you the same benefits as a char array, have you tried it with different initial capacities? Commented Jun 21, 2012 at 8:13

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

THat pretty much is it - reallocation DOES cost time. After that I would say you have to have VERY VERY VERY special code for the difference to REALLY make a difference.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.