¿Cuál es la forma más eficaz de dividir dos valores integrales y obtener un cociente de coma flotante en .NET?

StackOverflow https://stackoverflow.com/questions/283377

Pregunta

Considere la siguiente firma en C #:

double Divide(int numerator, int denominator);

¿Hay alguna diferencia de rendimiento entre las siguientes implementaciones?

return (double)numerator / denominator;

return numerator / (double)denominator;

return (double)numerator / (double)denominator;

Supongo que los dos anteriores devuelven la misma respuesta.

¿Me he perdido alguna otra solución equivalente?

¿Fue útil?

Solución

¿Ha intentado comparar el IL (por ejemplo, con 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; }

Los tres se convierten (dar o tomar el nombre):

.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
}

Entonces no: hay exactamente cero diferencia.

Otros consejos

Incluso si usa VB.NET, tanto el numerador como el denominador se convierten a dobles antes de hacer la división real, por lo que sus ejemplos son los mismos.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top