String V/s StringBuilder

With the help of my friend we did a small test to understand the behavior of StringBuilder and String in terms

 

  1. Execution Time
  2. Memory

We executed the following piece of code

 

 

class Program
    {
        ulong SessionID = 1000;
        ulong UserID = 292902;
        String GLOBESNAME = “XXX”;
        static void Main(string[] args)
        {
           
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i=0; i < 1000000; i++)
            {
                Program p = new Program();
                p.getXML();
                
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds.ToString());
            Console.Read();
        }
        private void getXML()
        {
            String xml = @”<INPUTXML>
                    <SESSIONID>” + SessionID.ToString() + @”</SESSIONID>
                    <USERID>” + UserID.ToString() + @”</USERID>
                    <GLOBESNAME>” + GLOBESNAME + @”</GLOBESNAME>
                    <LANGUAGE>ENGLISH</LANGUAGE>
                    <SEARCH>
                        <LOOKINGFORME>VAULT</LOOKINGFORME>
                        <LOOKINGFORMETYPE>ENTITY</LOOKINGFORMETYPE>
                        <LOOKINGFORMEREQUIRED>FALSE</LOOKINGFORMEREQUIRED>
                        <LOOKINGFOR>
                            <ACCESSTONAME>READ</ACCESSTONAME>
                        </LOOKINGFOR>
                    </SEARCH>
                </INPUTXML>”;
        }
    }
The getXML method was changed for StringBuilder.Append and StringBuilderAppenFormat.
StringBuilder.Append
===========================================================
          StringBuilder sb = new StringBuilder(500);
           sb.Append(@”<INPUTXML>
                    <SESSIONID>” + SessionID.ToString() + @”</SESSIONID>
                    <USERID>” + UserID.ToString() + @”</USERID>
                    <GLOBESNAME>” + GLOBESNAME + @”</GLOBESNAME>
                    <LANGUAGE>ENGLISH</LANGUAGE>
                    <SEARCH>
                        <LOOKINGFORME>VAULT</LOOKINGFORME>
                        <LOOKINGFORMETYPE>ENTITY</LOOKINGFORMETYPE>
                        <LOOKINGFORMEREQUIRED>FALSE</LOOKINGFORMEREQUIRED>
                        <LOOKINGFOR>
                            <ACCESSTONAME>READ</ACCESSTONAME>
                        </LOOKINGFOR>
                    </SEARCH>
                </INPUTXML>”);
For StringBuilder.AppendFormat
===========================================================
StringBuilder sb = new StringBuilder(500);
           sb.AppendFormat(@”<INPUTXML>
                    <SESSIONID>{0}</SESSIONID>
                    <USERID>{1}</USERID>
                    <GLOBESNAME>{2}</GLOBESNAME>
                    <LANGUAGE>ENGLISH</LANGUAGE>
                    <SEARCH>
                        <LOOKINGFORME>VAULT</LOOKINGFORME>
                        <LOOKINGFORMETYPE>ENTITY</LOOKINGFORMETYPE>
                        <LOOKINGFORMEREQUIRED>FALSE</LOOKINGFORMEREQUIRED>
                        <LOOKINGFOR>
                            <ACCESSTONAME>READ</ACCESSTONAME>
                        </LOOKINGFOR>
                    </SEARCH>
                </INPUTXML>”,SessionID,UserID,GLOBESNAME);
The reading for execution time was done through Stopwatch class and the reading for memory was taken using ANTS Profiler.
The idea was execute the getXML method 10,000,000 times and determine which out of three  methodology is best for string concatenation. The three method considered was
a. String
b. StringBuilder.Append
c. StringBuilder.AppendFormat
For StringBuilder we considered two cases
a. With inital capacity
b. With Capacity
 
the above was done only for execution time, we ignore this for Memory  load.
The results were SHOCKING compare to our belief. We are still not sure that we are right and would like comment from Microsoft CLR team about the behaviour.
The results for execution time is
The 500 in the above stats means that StringBuilder initial capacity was set to 500.
The readings for memory load taken using ANTS profiler is as follows
The columns are
a. Number of Objects Created.
b. Total Size for entire allocation.
c. Number of time the Garbage Collector was called.
The results are really SHOCKING. It seems concatination using String object is THE MOST EFFICIENT methodology. This is contradictary to what the internet have been saying since the inception of .NET.

ITS A REQUEST TO ALL, TO RUN THE ABOVE CODE AND SHARE YOUR RESULTS. WE ALSO REQUEST THE .NET CLR TEAM TO COMMENT ON THIS.

 

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.

 


 

 

 

 

One Year of Blogging

Its’s been a year that I have start writting which co-incidently co-incides with birth date of my late mother 9th April. I always wanted to be in this great world of blog but didn’t know how to go about it. Then come the great guy Rajgo my ex-boss motivational speech in weekly team meeting. Thanks to him I could start and now I’m proud of the fact I have a space of my own in this big world of Blogging. 

One year I posted some 37 posts many of them were just links. I started with some stupid stuff and then added I believe some good stuff on Adobe AIR and WCF. These post are getting the maximum hit so thought so they are good. Overall there 4033 hits on my blog in the first year. To me this figure means a lot. Now on a daily basis I get a hit count of 20-25 which is great for a beginner like me.

The only problem with my post I’m unable to write more about a particular topic due to the fact my work keeps on changing from topic to topic so unable to provide much insight into a topic like AIR and WCF. Will try aim those stuff for this year. Hopefully at this time by next year I have a better story to write.