java - Math.min() 和 if 条件之间的区别

标签 java

什么方法是获得最少数量的最佳方法,并且可以提高性能,或者两者都与性能相同?

获取两个数字之间的最小距离的一种方法:

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.00.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.00.0,但可以说它更具可读性 - 您需要首先考虑特殊情况是否适用,然后再考虑可读性与(非常轻微的)性能差异。

我个人会使用 Math.min,但这是我自己的观点。

关于java - Math.min() 和 if 条件之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33167306/

相关文章:

java - H2数据库存储在哪里?

java - 在 Linux OpenSuse cron 上,脚本运行,但只生成空日志

java - 为什么 "3.5".matches ("[0-9]+") 返回 false?

java - Spring 启动 : Error in API access : Failed to connect to <domainName>

java - 使用 Java 在 Ubuntu 中获取音频设备名称

java - Python 脚本不会在本地主机 gae 开发服务器的 urlopen 之后读取()——对等连接重置

java - 在 Selenium Webdriver 中显式等待 findElements

java - 如何告知比较使用的方法

java - 如何在处于接收状态时关闭 DatagramSocket

java - Springboot -> Springboot 2 : 2 Spring WebApplicationInitializers detected on classpath