Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I improve the "double.IsNaN( x )" function call on embedded C#?

Tags:

performance

c#

I´ve a line of code that is called millions of times inside a for loop, checking if a passed argument is double.NaN. I´ve profiled my application and one of the bottlenecks is this simple function:

public void DoSomething(double[] args)
{
    for(int i = 0; i < args.Length;i++)
    {
       if(double.IsNan(args[i]))
       {
         //Do something
       }
    }
}

Can I optimize it even if I can´t change the code inside the if?

like image 316
Hbas Avatar asked Nov 28 '22 19:11

Hbas


1 Answers

If you have really optimized other parts of your code, you can let this function become a little bit cryptic an utilize the definition of Not a Number (NaN):

"The predicate x != y is True but all others, x < y , x <= y , x == y , x >= y and x > y , are False whenever x or y or both are NaN.” (IEEE Standard 754 for Binary Floating-Point Arithmetic)

Translating that to your code you would get:

public void DoSomething(double[] args)
{
    for(int i = 0; i < args.Length;i++)
    {
       double value = args[i];  
       if(value != value)
       {
         //Do something
       }
    }
}

In an ARM device using WindoWs CE + .NET Compact Framework 3.5 with around 50% probability of getting a Nan, value != value is twice as fast as double.IsNan(value).

Just be sure to measure your application execution after!

like image 152
Hbas Avatar answered Feb 08 '23 23:02

Hbas