1

C# で次の署名を検討してください。

double Divide(int numerator, int denominator);

次の実装の間にパフォーマンスの違いはありますか?

return (double)numerator / denominator;

return numerator / (double)denominator;

return (double)numerator / (double)denominator;

上記の両方が同じ答えを返すと仮定しています。

他の同等のソリューションを見逃しましたか?

4

2 に答える 2

5

IL を (たとえば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; }

3つすべてが次のようになります(名前を付けるか取る):

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

いいえ、違いはまったくありません。

于 2008-11-12T09:06:56.077 に答える
1

VB.NETを使用している場合でも、実際の除算を行う前に分子と分母の両方が倍精度に変換されるため、例は同じです。

于 2008-11-12T09:14:48.667 に答える