Pref: Convert.ToString() or Int32.ToString()

A reader recently asked me if there is any perf difference between Convert.ToString() or Int32.ToString().

 

If you search for Convert.cs you will find the Rotor source for Convert.cs which helps answer the question…

 02066         public static string ToString(int value) {
02067             return value.ToString();
02068         }

As you can see, all Convert.ToString() does it call value.ToString(). The call is simple enough that it is likely to get inlined. So I can’t imagine their being any noticeable differences.

But we should of course, measure… so on a very noise laptop running the latest Whidbey CTP I ran this test:

ToString Test: 00:00:16.0299278

Convert Test: 00:00:16.4424654

Press any key to continue . . .

As you can see, there is almost no difference between these two. So net: you should use which ever one feels more natural to you in your project.

Here is the code if you want to play with it:

using System;

using System.Collections.Generic;

using System.Diagnostics;

class Program

{

    static int iterations = 50000000;

    static void Main(string[] args)

    {

        //do one round just to worm up...

        for (int i = 0; i < iterations; i++)

        {

            i.ToString();

            Convert.ToString(i);

        }

        Stopwatch sw = new Stopwatch();

        //Do the ToString() test

        sw.Start();

        for (int i = 0; i < iterations; i++)

        {

            i.ToString();

        }

        sw.Stop();

        Console.WriteLine("ToString Test: {0}", sw.Elapsed);

        sw.Reset();

        //Do the Convert() test

        sw.Start();

        for (int i = 0; i < iterations; i++)

        {

            Convert.ToString(i);

        }

        sw.Stop();

        Console.WriteLine("Convert Test: {0}", sw.Elapsed);

    }

}

 

update: just fixed some formatting