.NETで2つの整数値を除算し、浮動小数点商を取得する最もパフォーマンスの高い方法は何ですか?

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

質問

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

double Divide(int numerator, int denominator);

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

return (double)numerator / denominator;

return numerator / (double)denominator;

return (double)numerator / (double)denominator;

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

他の同等のソリューションを見逃したことはありますか?

役に立ちましたか?

解決

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
}

そのため、違いはまったくありません。

他のヒント

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top