我有两个整数,例如val a = 5和val b = 7。我只是好奇计算这些整数的最小值的最快方法是什么。
val min = minOf(a,b)
val min = Math.min(a,b)
val min = if(a<b) a else b 
你能告诉我哪个更快,为什么那个更快?
它们都同样快。
如果你看一下函数的定义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;
}
事实上,这是你的第三个选择。
| 归档时间: | 
 | 
| 查看次数: | 6459 次 | 
| 最近记录: |