https://kotlinlang.org logo
Title
k

keishi kubo

02/24/2020, 1:59 PM
I couldn’t understand inline function explanation. Can anyone explain ?
Using higher-order functions imposes certain runtime penalties: each function is an object, and it captures a closure, i.e. those variables that are accessed in the body of the function. Memory allocations (both for function objects and classes) and virtual calls introduce runtime overhead.
But it appears that in many cases this kind of overhead can be eliminated by inlining the lambda expressions.
s

satyan

02/24/2020, 2:02 PM
inline is more or less moving the function body to the call site on compilation Without inlining
each function is an object, and it captures a closure
👍 1
k

keishi kubo

02/24/2020, 2:17 PM
I don’t fully understand compiler, but I understand a bit. Just run procedures inside inline has less overhead than Making a function object and run procedures inside the function ?
e

Evan R.

02/24/2020, 3:31 PM
When you normally invoke a function, it requires a couple of steps: 1. the function call is added onto the stack 2. The parameters are copied onto the stack for local use within the function 3. When the function completes, the return value must be copied back to the call site This has numerous downsides, esp. with functions which take lambdas e.g. `.forEach { }`: 1. You can’t do a
continue
or
return
from inside the passed lambda targeting an outside function or loop 2. You incur the overhead of copying all the required values into the function call To avoid this, you can write an “inline function” which, instead of doing all that copy and stack stuff, the compiler will just copy-paste the code from your inline function to the place you’re calling it. For example, when the following is compiled:
inline fun printlnYell(message: String) {
    println(message.toUpperCase())
}

fun main() {
  printlnYell("Hello world")
}
The bytecode will represent something more like this:
fun main() {
    println("Hello world".toUpperCase())
}
👍 3
💯 2
k

keishi kubo

02/25/2020, 3:51 PM
Thank you ! @Evan R. very very well explained!
e

Evan R.

02/25/2020, 3:55 PM
No problem!
😀 1