什么方法是获得最少数量的最佳方法,并且可以提高性能,或者两者都与性能相同?
获取两个数字之间的最小距离的一种方法:
double minDistance = Double.MAX_VALUE;
double distance = coordinate1.distnaceTo(coordinate2);
if(distnace < minDistance ) {
minDistance = distance;
}
获取两个数字之间的最小距离的另一种方法:
double minDistance = Double.MAX_VALUE;
double minDistance = Math.min(coordinate1.distnaceTo(coordinate2), minDistance);
最佳答案
如果您处理的是正数,不等于 NaN
、-0.0
或 0.0
,那么应该没有太大区别.
以下来自 Java 8 中的 Math.min
源代码突出显示了以下差异:
If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero. If one argument is positive zero and the other is negative zero, the result is negative zero.
因此,Math.min
的效率可能稍低,因为它检查 NaN
和 -0.0
与 0.0
,但可以说它更具可读性 - 您需要首先考虑特殊情况是否适用,然后再考虑可读性与(非常轻微的)性能差异。
我个人会使用 Math.min
,但这是我自己的观点。
关于java - Math.min() 和 if 条件之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33167306/