什么是在.NET中划分两个整数值并获得浮点商的最高效方法?

Dre*_*kes 1 .net floating-point performance division integral

考虑C#中的以下签名:

double Divide(int numerator, int denominator);
Run Code Online (Sandbox Code Playgroud)

以下实现之间是否存在性能差异?

return (double)numerator / denominator;

return numerator / (double)denominator;

return (double)numerator / (double)denominator;
Run Code Online (Sandbox Code Playgroud)

我假设上述两个都返回相同的答案.

我错过了其他任何等效解决方案吗?

Mar*_*ell 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; }
Run Code Online (Sandbox Code Playgroud)

这三个人都成了(给予或取名):

.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
}
Run Code Online (Sandbox Code Playgroud)

所以没有:差别确实是零.