TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Duh: Casting vs. Convert.ToXXX

I was curious, so I disassembled Convert.ToInt32 using reflector (you can also view the source code on rotor @ http://www.123aspx.com/Rotor/RotorSrc.aspx?rot=39959) and you'll see why it is so much slower. Every line highlighted in yellow gets executed in the loop that I wrote, so it's just a lot more processing instructions to use Convert rather than casting...
 

public static int ToInt32(double value)

{

    if (value >= 0)

    {

        if (value >= 2147483647.5)

        {

            throw new OverflowException();

        }

        int num1 = (int) value;

        double num2 = value - num1;

        if ((num2 > 0.5) || ((num2 == 0.5) && ((num1 & 1) != 0)))

        {

            num1++;

        }

        return num1;

    }

    if (value >= -2147483648.5)

    {

        int num3 = (int) value;

        double num4 = value - num3;

        if ((num4 < -0.5) || ((num4 == -0.5) && ((num3 & 1) != 0)))

        {

            num3--;

        }

        return num3;

    }

    throw new OverflowException();

}


Digg!

posted on Friday, July 15, 2005 5:58 PM

Feedback

No comments posted yet.