I am looking for the fastest way to determine if there is at least one NaN in a float array.
Let's say I have an array of floats:
var a = float[10000];
I can do this:
(let's ignore the loop itself, I know foreach it not the most efficient, it is just to illustrate)
bool hasNan(ref float[] floats)
{
foreach (var f in floats)
{
if (float.IsNaN(f)) return True;
}
return False;
}
We know that in most cases, there are no NaNs, so I have to scan the whole array anyways. Instead of calling IsNaN for every element, would it make sense to:
The array is quite large and this is happening in a fairly tight timeframe as I'm processing streams of financial data coming in realtime.
Edit:
Check the fiddle: https://dotnetfiddle.net/W3VgQg
and look at the IL code generated.
When doing the float.IsNan method, the code is not inlined. The sum method seems faster, but I don't know enough about IL to really understand the details.
User contributions licensed under CC BY-SA 3.0