【发布时间】:2014-08-11 11:07:42
【问题描述】:
我在.NET Source Code 中发现了这个:它声称比System.Double.IsNaN 快100 倍。是否有理由不使用此功能而不是System.Double.IsNaN?
[StructLayout(LayoutKind.Explicit)]
private struct NanUnion
{
[FieldOffset(0)] internal double DoubleValue;
[FieldOffset(0)] internal UInt64 UintValue;
}
// The standard CLR double.IsNaN() function is approximately 100 times slower than our own wrapper,
// so please make sure to use DoubleUtil.IsNaN() in performance sensitive code.
// PS item that tracks the CLR improvement is DevDiv Schedule : 26916.
// IEEE 754 : If the argument is any value in the range 0x7ff0000000000001L through 0x7fffffffffffffffL
// or in the range 0xfff0000000000001L through 0xffffffffffffffffL, the result will be NaN.
public static bool IsNaN(double value)
{
NanUnion t = new NanUnion();
t.DoubleValue = value;
UInt64 exp = t.UintValue & 0xfff0000000000000;
UInt64 man = t.UintValue & 0x000fffffffffffff;
return (exp == 0x7ff0000000000000 || exp == 0xfff0000000000000) && (man != 0);
}
编辑:还是according to the .NET Source Code,System.Double.IsNaN 的代码如下:
public unsafe static bool IsNaN(double d)
{
return (*(UInt64*)(&d) & 0x7FFFFFFFFFFFFFFFL) > 0x7FF0000000000000L;
}
【问题讨论】:
-
嗯,评论说它更快,所以它可能更快......你有基准测试吗?这是一个有趣的问题(尤其是“使用较慢的任何理由”部分。
-
在不知道任何关于测试 NaN 或此方法的正确性的情况下,我建议坚持使用 .NET 实现,假设存在任何性能差异的充分理由。 .NET 开发人员知道他们在做什么,并且必须考虑所有边缘情况等,以生成一个强大的库。
-
好吧,那个类是
internal,所以你最终会复制那个源代码并且必须维护它以备将来使用。 -
@paqogomez 不是真的。这是一个有趣的问题。
-
@paqogomez 我读过这篇引文的次数,我开始讨厌它了……这不是这里的主题。
标签: c# floating-point nan