ما هي الطريقة الأكثر performant للتقسيم قيمتين متكاملة والحصول على القسمة نقطة عائمة في. NET؟
-
08-07-2019 - |
سؤال
والنظر في توقيع التالية في C #:
double Divide(int numerator, int denominator);
هل هناك فرق بين أداء التطبيقات التالية؟
return (double)numerator / denominator;
return numerator / (double)denominator;
return (double)numerator / (double)denominator;
وأفترض أن كل ما سبق إرجاع نفس الجواب.
وقد فاتني أي حل يعادل الآخرين؟
المحلول
هل حاولت مقارنة IL (على سبيل المثال، مع العاكس )؟
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
}
وليس لذلك: هناك فرق صفر بالضبط
نصائح أخرى
وحتى إذا كنت تستخدم VB.NET، يتم تحويل كل من البسط والمقام على الزوجي قبل القيام تقسيم الفعلي، لذلك أمثلة الخاصة بك هي نفسها.
لا تنتمي إلى StackOverflow