TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Performance: Casting vs. Convert.ToXXX()

Maybe I'm missing something, but there seems to be a significant difference in performance where casting is about 2.5 times faster than using Convert.ToInt32. That is, at least for converting from double to int...

using System;

using System.Runtime.InteropServices;

 

class App {

 

    [DllImport("Kernel32.dll")]

    private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

 

    [DllImport("Kernel32.dll")]

    private static extern bool QueryPerformanceFrequency(out long lpFrequency);

 

    [STAThread]

    static void Main(string[] args) {

        const int MAX = 100000000;

 

        double[] nums = new double[MAX];

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

        {

            nums[i] = (double) i;

        }

 

        long startTime, endTime, freq;

        QueryPerformanceFrequency(out freq);

        QueryPerformanceCounter(out startTime);

 

        foreach(double d in nums)

        {

            //casting in C# is about 2.5 times faster than Convert.ToInt32

            int i = (int) d;

            //int i = Convert.ToInt32(d);

        }

 

        QueryPerformanceCounter(out endTime);

        Console.WriteLine("frequency: {0:n0}", freq);

        Console.WriteLine("time: {0:n5}s", (endTime - startTime)/(double) freq);

    }

}

Digg!

posted on Friday, July 15, 2005 10:07 AM

Feedback

No comments posted yet.