I couldn’t understand inline function explanation...
# getting-started
k
I couldn’t understand inline function explanation. Can anyone explain ?
Copy code
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
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
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
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:
Copy code
inline fun printlnYell(message: String) {
    println(message.toUpperCase())
}

fun main() {
  printlnYell("Hello world")
}
The bytecode will represent something more like this:
Copy code
fun main() {
    println("Hello world".toUpperCase())
}
👍 3
💯 2
k
Thank you ! @Evan R. very very well explained!
e
No problem!
😀 1