StringBuilder gotcha

We all know that concatenating the strings is a bad practice

“String A”+”String B” (evil)

and that we should use


StringBuilder sb = new StringBuilder();sb.Append(“String A”);sb.Append(“String B”);sb.Append(“String C”);

We should do that because the strings are immutable (unchangeable) and every concatenation of the strings means allocating a new immutable block on the heap and putting in it both concatenated strings which is very bad for performances. StringBuilder is supposed to save that by reserving the certain NON immutable space in heap where we could add “for real the strings without the burden of allocating new blocks on the heap.

But, there’s a catch in the fact that  default constructor of string builder (without parameters) is resulting with allocation of “non immutable space” for strings up to 16 characters

Therefore, if the string builder append strings which total character counts more then 16 the heap allocation occurs like in the case of concatenating the strings.

In the example stated in this post before the “String C” would be append the CLR would have to allocate a new 16 byte heap fragment for the *new* string builder copy the result of *old* string builder in it and then add the “String C” in it.

Simple console application which illustrates the problem

using System;using System.Text; namespace StringBuilder_tip{    class Program    {        static void Main(string[] args)        {            StringBuilder sb = new StringBuilder();            sb.Append(“String A”);            Console.WriteLine(sb.Capacity);            sb.Append(“String B”);            Console.WriteLine(sb.Capacity);            sb.Append(“String C”);            Console.WriteLine(sb.Capacity);             Console.ReadKey();        }    }


RULE  OF THUMB: Always try to estimate the length of the string builder. In cases when the result string length is not defiantly less the 16 chars, it is better to oversize the capacity, then to rely on default parameterizes constructor



Posted on December 20, 2006, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: