Double.IsNaN test 100 times faster?

后端 未结 3 1520
无人及你
无人及你 2021-01-01 09:45

I found this in the .NET Source Code: It claims to be 100 times faster than System.Double.IsNaN. Is there a reason to not use this function instead of Sys

3条回答
  •  暖寄归人
    2021-01-01 10:14

    Here's a naive benchmark:

    public static void Main()
    {
        int iterations = 500 * 1000 * 1000;
    
        double nan = double.NaN;
        double notNan = 42;
    
        Stopwatch sw = Stopwatch.StartNew();
    
        bool isNan;
        for (int i = 0; i < iterations; i++)
        {
            isNan = IsNaN(nan);     // true
            isNan = IsNaN(notNan);  // false
        }
    
        sw.Stop();
        Console.WriteLine("IsNaN: {0}", sw.ElapsedMilliseconds);
    
        sw = Stopwatch.StartNew();
    
        for (int i = 0; i < iterations; i++)
        {
            isNan = double.IsNaN(nan);     // true
            isNan = double.IsNaN(notNan);  // false
        }
    
        sw.Stop();
        Console.WriteLine("double.IsNaN: {0}", sw.ElapsedMilliseconds);
    
        Console.Read();
    }
    

    Obviously they're wrong:

    IsNaN: 15012

    double.IsNaN: 6243


    EDIT + NOTE: I'm sure the timing will change depending on input values, many other factors etc., but claiming that generally speaking this wrapper is 100x faster than the default implementation seems just wrong.

提交回复
热议问题