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

这三个都变成(给或取名字):

.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 回答