在kotlin中获得两个或多个整数的最小值的最快方法是什么?
我有两个整数,比如在kotlin中获得两个或多个整数的最小值的最快方法是什么?,kotlin,Kotlin,我有两个整数,比如vala=5和valb=7。我只是好奇,计算这些整数的最小值的最快方法是什么 val min=minOf(a,b) valmin=Math.min(a,b) val min=if(a它们都同样快 如果查看minOf()函数的定义,您会看到 /** * Returns the smaller of two values. */ @SinceKotlin("1.1") @kotlin.internal.InlineOnly public actual in
vala=5
和valb=7
。我只是好奇,计算这些整数的最小值的最快方法是什么
val min=minOf(a,b)
valmin=Math.min(a,b)
val min=if(a它们都同样快
如果查看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;
}
/**
*返回两个{@code int}值中较小的值。即,
*结果使参数更接近
*{@link Integer#MIN_VALUE}。如果参数相同
*值,结果是相同的值。
*
*@param a是一个参数。
*@param b另一个参数。
*@返回{@code a}和{@code b}中的较小者。
*/
公共静态最小整数(整数a、整数b){
返回(a很可能它们的速度都完全相同。minOf
与Math.min
完全相同,因为它是内联的,并且Math.min
使用与第三个块相同的逻辑。函数调用通常是优化的,编译器甚至可以内联它,因此不会有任何区别。我建议您阅读此答案。另外,如果您真的非常关心性能,那么就不要使用JVM……这个答案并不能解释为什么函数调用的开销可能不太大。