Qual è il modo più efficace per dividere due valori integrali e ottenere un quoziente in virgola mobile in .NET?

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

Domanda

Considera la seguente firma in C #:

double Divide(int numerator, int denominator);

C'è una differenza di prestazioni tra le seguenti implementazioni?

return (double)numerator / denominator;

return numerator / (double)denominator;

return (double)numerator / (double)denominator;

Suppongo che entrambi i precedenti restituiscano la stessa risposta.

Ho perso qualche altra soluzione equivalente?

È stato utile?

Soluzione

Hai provato a confrontare l'IL (ad esempio, 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; }

Tutti e tre diventano (dare o prendere il nome):

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

Quindi no: c'è esattamente la differenza zero.

Altri suggerimenti

Anche se usi VB.NET, sia il numeratore che il denominatore vengono convertiti in doppi prima di fare la divisione effettiva, quindi i tuoi esempi sono gli stessi.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top