Sunday, October 3, 2010

String.Format performance

C# string performance is a tricky problem. I have two functions which generate the same result. Personally I prefer the second one because it is just an elegant representation format. Well, you have to pay for the elegance.

A's performance is much faster than B's.

         public static void A()
        {
            var s = "abc" + "bcd" + "1" + "2" + "3";
        }

        public static void B()
        {
            var s = String.Format("{0}{1}{2}{3}{4}", "abc", "bcd", "1", "2", "3");
        }

the following is the elapsed ticks for function A and B. If I run 100 iterations, A wins 99 times.


A=14 B=344

Let me try something different, maybe my favorite format has some advantages. Most of time, we do not use String.Format to construct a string, we pass in some non-string type.


        public static void A()
        {
            var s = "abc" + "bcd" + 1.ToString() + 2.ToString() + 3.ToString() + 4.ToString() + 5.ToString();
        }

        public static void B()
        {
            var s = String.Format("{0}{1}{2}{3}{4}{5}{6}", "abc", "bcd", 1, 2, 3, 4, 5);
        }

I am so happy that when this time, the String.Format catches up.


A=1609 B=585

I dig into the IL code and find that:

Function A will calls into "77 : Call System.String System.String.Concat(System.String[])".
While B will invoke: "75 : Call System.String System.String.Format(System.String, System.Object[])"

the different is not from these two functions, the difference is because A has to call ToString() several times and convert the result into a string array. A only need to pass the object reference to the Format.

No comments: