Sobes.tech
Junior — Middle

Millistel juhtudel on soovitatav kasutada inline-funktsiooni koodis?

sobes.tech AI

Vastus AI-lt

The inline function in Kotlin is recommended for small functions that are called frequently, especially if they accept lambda expressions as parameters. This allows the compiler to insert the function body directly at the call site, reducing call overhead and potentially improving performance.

Use inline when:

  • The function is short and called often.
  • The function accepts lambdas to avoid creating additional objects and calls.
  • It is necessary to reduce call overhead in performance-critical places.

Example:

inline fun measureTime(block: () -> Unit) {
    val start = System.currentTimeMillis()
    block()
    val end = System.currentTimeMillis()
    println("Execution time: ${end - start} ms")
}

// Usage
measureTime {
    // code whose execution time needs to be measured
}