【问题标题】:What is fastest way to get minimum of two or more integers in kotlin?在 kotlin 中获得最少两个或多个整数的最快方法是什么?
【发布时间】:2020-12-25 02:59:49
【问题描述】:

我有两个整数,例如 val a = 5val b = 7。我只是对计算这些整数的最小值的最快方法感到好奇。

val min = minOf(a,b)
val min = Math.min(a,b)
val min = if(a<b) a else b 

你能告诉我哪个更快,为什么更快?

【问题讨论】:

  • 很可能它们都具有完全相同的速度。 minOfMath.min 完全相同,因为它是内联的,Math.min 使用与第三个块中相同的逻辑。函数调用通常是优化的,编译器甚至可能内联它,所以根本没有区别。我建议你阅读这个答案stackoverflow.com/a/6495096/5288316。另外,如果您真的很在意性能,请不要使用 JVM...

标签: kotlin


【解决方案1】:

它们都同样快。

如果您查看minOf() 函数的定义,您会看到

/**
* Returns the smaller of two values.
 */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public actual inline fun minOf(a: Int, b: Int): Int {
    return Math.min(a, b)
}

实际上,这是您的第二个选择。

那么,Math.min() 的正文是

/**
 * Returns the smaller of two {@code int} values. That is,
 * the result the argument closer to the value of
 * {@link Integer#MIN_VALUE}.  If the arguments have the same
 * value, the result is that same value.
 *
 * @param   a   an argument.
 * @param   b   another argument.
 * @return  the smaller of {@code a} and {@code b}.
 */
public static int min(int a, int b) {
    return (a <= b) ? a : b;
}

事实上,这是您的第三个选择。

【讨论】:

  • 这个答案没有解释为什么函数调用的开销可能并不显着。
猜你喜欢
  • 1970-01-01
  • 2019-10-11
  • 2012-03-15
  • 2022-01-20
  • 1970-01-01
  • 2012-12-06
  • 2022-01-13
  • 1970-01-01
  • 2023-02-01
相关资源
最近更新 更多