Performance of "string concatenation"

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

Every developer knows that string concatenation is something you should avoid when performance is required. In such cases StringBuilder should be used instead or sometimes even String.Format. However, this is not always true.

 

Following example shows that there are common situations which do not match this subjective rule. The code example shows three methods doing the same thing. The table bellow shows results of the performance session. The most right column is the “Elapsed Inclusive time”, which shows how much time certain method has taken.

 

The profiling has been done by using of Visual Studio 2005 Performance Tools.

 

      static void Main(string[] args)

      {

            for (int n = 0; n < 3000; n++)

            {

                concat();

                format();

                stringbuilder();

            }

      }

 

        static string tmp = "2222222222222222222";

 

        private static string m_Txt = "{0}|{1}|{2}|{3}|{4}|{5}";

 

        public static string concat()

        {

            return tmp + "|" + tmp + tmp + "|" + tmp + tmp + "|" + tmp;

        }

 

        public static string format()

        {

            return String.Format(m_Txt, tmp, tmp, tmp, tmp, tmp, tmp);

        }

 

 

        public static string stringbuilder()

        {

            System.Text.StringBuilder sb = new StringBuilder();

            sb.Append(tmp);

            sb.Append(tmp);

            sb.Append(tmp);

            sb.Append(tmp);

            sb.Append(tmp);

            sb.Append(tmp);

         

            return sb.ToString();

        }

 

method         calls                   Elapsed Inclusive time

-----------------------------------------------------

 concat          3000 2.023159      7.797580 

 format          3000 1.872206    14.493630 

 stringbuilder  3000 4.543095    17.300266 

------------------------------------------------------

 

Damir Dobric


Posted Mar 08 2006, 07:47 AM by Damir Dobric
Filed under:

Comments

Scott Munro wrote re: Performance of &quot;string concatenation&quot;
on 03-08-2006 10:16
In defence of the StringBuilder, this is a scenario to which it is not suited. The overhead of instantiating a StringBuilder object is not warranted for the concatenation of only six strings.

If you had written the test so that only a single StringBuilder object was used then it would have produced better results.

The results do have an important message though. Don't overuse the StringBuilder. For smaller jobs, simple concatenation is more efficient.
developers.de is a .Net Community Blog powered by daenet GmbH.