对于这种情况,我的假设是否正确:
double d = 3.76212; // d >= 0 && d <= Int32.MaxValue
一个人应该总是使用这个:
double truncated = (double)(int)d;
而不是这些:
double truncated = Math.Truncate(d); // 4 times slower than (double)(int) on x86, 7 times slower than (double)(int) on x64
double truncated = Math.Floor(d); // 3 times slower than (double)(int) on both x86 and x64
换句话说,只有在处理足够大的数字(x86 上 >Int32.MaxValue 和 x64 上 > Int64.MaxValue)或处理小于 0 的数字时才会使用 Math.Floor,因为 Floor 与负数的行为不同?至于 Truncate,它的使用确实应该受到限制(缺少不能放入 Int32 或 Int64 中的非常大的负数),因为它在所有情况下都比 Floor 慢?
最佳答案
我认为我们不能假设在 Framework 的 future 版本或 CLR 的 future 版本中会一直如此。
您可以做的是创建一个您调用的简单辅助类,然后将实现细节隐藏在该类中。然后,当出现新的 CLR/Framework 时,您可以重新进行测量并根据需要更新帮助程序类:
double truncated = FastMath.Truncate(d);
并按照
public static double Truncate(double d)
{
if ((d >= Int32.MinValue) && (d <= Int32.MaxValue))
{
...
}
}
关于c# - Math.Floor 或 Math.Truncate 与 (int) 在正数性能方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25424880/