views:

433

answers:

2

Consider the following signature in C#:

double Divide(int numerator, int denominator);

Is there a performance difference between the following implementations?

return (double)numerator / denominator;

return numerator / (double)denominator;

return (double)numerator / (double)denominator;

I'm assuming that both of the above return the same answer.

Have I missed any other equivalent solution?

+5  A: 

Have you tried comparing the IL (for example, with Reflector)?

static double A(int numerator, int denominator)
{ return (double)numerator / denominator; }

static double B(int numerator, int denominator)
{ return numerator / (double)denominator; }

static double C(int numerator, int denominator)
{ return (double)numerator / (double)denominator; }

All three become (give or take the name):

.method private hidebysig static float64 A(int32 numerator, int32 denominator) cil managed
{
    .maxstack 8
    L_0000: ldarg.0 // pushes numerator onto the stack
    L_0001: conv.r8 // converts the value at the top of the stack to double
    L_0002: ldarg.1 // pushes denominator onto the stack
    L_0003: conv.r8 // converts the value at the top of the stack to double
    L_0004: div     // pops two values, divides, and pushes the result
    L_0005: ret     // pops the value from the top of the stack as the return value
}

So no: there is exactly zero difference.

Marc Gravell
+1  A: 

Even if you use VB.NET, both numerator and denominator are converted to doubles before doing the actual division, so your examples are the same.