SYSK 16: How StringBuilder works, or on the importance of StringBuilder initialization

We all know that strings in .NET are immutable; i.e. code that appears to change a String actually makes another one, leaving the old one for garbage collection.  To improve string concatenation performance, Microsoft has a StringBuilder class.

Did you know that StringBuilder works by allocating more memory than you need, and by tacking the new strings into that buffer. Every time you need the buffer to enlarge, it doubles in size. That approach was chosen as a trade-off between allocating too much memory and wasting a lot of time allocating little extra bits over and over again. The starting size is implementation-specific, but in most cases it's 16 characters. You can pass an integer to the StringBuilder constructor to tell it the which starting size of this instance to use.  Note:  you don't need to worry too much about getting it perfect -- if you chose the suggested starting size too small, the StringBuilder will extend it for you.  As a rule of thumb, make a best guestimate on the resulting object size, and initialize the StringBuilder with the double of that.


Comments (0)

Skip to main content