StringBuilder Performance

C# programmers typically uses StringBuilder avoid creation too many string while concatenation operation. This is good practice and should be adopted everywhere. But normally we tend to do the following

StringBuilder sb = new StringBuilder();

and creates a program where there is too much load on .NET Memory manager. Let me explain it.

 

      1.  Creating an instance of StringBuilder using the deafult constructor causes  
                        StringBuilder sb = new StringBuilder();  

an instance of StringBuilder to be created with a size of 16 bytes.

          

    2.  Now when AppendFormat or Append is called on the StringBuilder instance
        sb.Append(“WordPress”);

   3.  It internally checks whether the string can fit within the existing StringBuilder instance.

    

    4. If there is enough then it appends to the existing.

    5. If there is not enough space it allocate the new String object and copies the entire string into it.

    6. This is where it hit the most as the allocation of new object is expensive and copying adds to the overhead.

    7. To overcome this issue always provide a size that is nearest to the length of the string.

         StringBuilder sb = new StringBuilder(400);

     8. This will really help to avoid calling .NET memory manager for each Append String call and thus taking away the benefit that is provided by the StringBuilder class.

Please write back if you feel something needs to add.

 


 

 

 

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: