June 4, 2012

String Builder Append vs String Concate vs String Format vs StringBuilder AppendFormat vs Ordinary Concatenation

Which one is faster method.?
   1:  string str1 = string.Format("{0}{1}{2}{3}{4}","String1","String2","String3","String4","String5");
   2:  string str2 = new StringBuilder().Append("String1").Append("String2").Append("String3").Append("String4").Append("String5");
   3:  string str3 = string.Concat(new string [] { "String1", "String2", "String3", "String4", "String5"});
   4:  string str4 = "String1" + "String2" + "String3" + "String4" + "String5";

You may think string builder or string concate but result is over 1 lakh iterations traditional "+" Operator faster in terms of memory and time.

Why traditional "+" Operator faster:
Reason behind traditional "+" Operator faster is it used String.Concat with length.
compiler convert this piece of code:
   1:  string str = "String1" + "String2" + "String3" + "String4" + "String5";
to this
   1:  string str = String.Concat(new Object[] { "String1", "String2", "String3", "String4", "String5"});

To do traditional zippy concatenation like above, don't confuse yourself, just use traditional "+" concatenation that's enough, c# does jobs for you..

No comments:

Post a Comment

Recommended Post Slide Out For Blogger