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