Friday, November 4, 2011

StringBuilder

We all know that a StringBuilder object should be used when we are concatenating a sizeable number of strings.

It seems the default capacity is 16. The default maximum capacity is 2147483647 (Int32.MaxValue), which is around 2 gigs, since Int32 can store 4G different values, from -2G to 2G-1.

The value of 16 was surprising. I thought it would be much higher than that. So, in my app where I need to load about 300MB into a StringBuilder object, I guess it is better to use it with a sizeable initial capacity. The initial capacity is also used as a delta when it runs out of the initial capacity. So, choose it wisely. I like to use a value that is a tradeoff between asking for a memory allocation every 16 bytes, and asking for all (like 300MB) in 1 or 2 allocations. For my current app, I have used it as 10MB.

StringBuilder sb = new StringBuilder(10 * 1024 * 1024);

Reference: http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

No comments:

Post a Comment