在 kotlin 中获取两个或多个整数中的最小值的最快方法是什么?

Tuq*_*qay 3 kotlin

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

val min = minOf(a,b)
Run Code Online (Sandbox Code Playgroud)
val min = Math.min(a,b)
Run Code Online (Sandbox Code Playgroud)
val min = if(a<b) a else b 
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*rra 6

它们都同样快。

如果你看一下函数的定义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)
}
Run Code Online (Sandbox Code Playgroud)

事实上,这是你的第二个选择。

那么, 的本体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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这个答案并没有解释为什么函数调用的开销可能并不显着。 (2认同)