1

I have two integers like val a = 5 and val b = 7. I just got curious about what is the fastest way to compute the minimum of these integers.

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

Can you tell me which one is faster and why that is faster?

Tugay
  • 2,057
  • 5
  • 17
  • 32
  • 5
    Most likely they all have the exact same speed. `minOf` is the exact same as `Math.min` since it's inlined, and `Math.min` uses the same logic as in your third block. Function calls are often optimized, the compiler may even inline it so there would be no difference at all. I suggest you read this answer https://stackoverflow.com/a/6495096/5288316. Also, if you really care about performance to that point, don't use the JVM... – Nicolas Sep 06 '20 at 14:02

2 Answers2

6

They are all equally fast.

If you look at the definition of the minOf() function, you see

/**
* 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)
}

that is, in fact, your second option.

Then, the body of Math.min() is

/**
 * 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;
}

that is, in fact, your third option.

Luca Murra
  • 1,848
  • 14
  • 24
  • 2
    This answer doesn't explain why the overhead of a function call might not be significant. – gidds Sep 06 '20 at 17:33
1

KOTLIN 1.8.0

The latest one is below and working fine.

  1. Latest : a.coerceAtMost(b)

  2. Deprecated but still can use : Math.min(a, b)

  3. Legacy : if(a>b) b else a

have a good day !

Yogendra
  • 4,817
  • 1
  • 28
  • 21