Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

when to use an inline function in Kotlin?

I know that an inline function will maybe improve performance & cause the generated code to grow, but I'm not sure when it is correct to use one.

lock(l) { foo() }

Instead of creating a function object for the parameter and generating a call, the compiler could emit the following code. (Source)

l.lock()
try {
  foo()
}
finally {
  l.unlock()
}

but I found that there is no function object created by kotlin for a non-inline function. why?

/**non-inline function**/
fun lock(lock: Lock, block: () -> Unit) {
    lock.lock();
    try {
        block();
    } finally {
        lock.unlock();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

Let's say you create a higher order function that takes a lambda of type () -> Unit (no parameters, no return value), and executes it like so:

fun nonInlined(block: () -> Unit) {
    println("before")
    block()
    println("after")
}

In Java parlance, this will translate to something like this (simplified!):

public void nonInlined(Function block) {
    System.out.println("before");
    block.invoke();
    System.out.println("after");
}

And when you call it from Kotlin...

nonInlined {
    println("do something here")
}

Under the hood, an instance of Function will be created here, that wraps the code inside the lambda (again, this is simplified):

nonInlined(new Function() {
    @Override
    public void invoke() {
        System.out.println("do something here");
    }
});

So basically, calling this function and passing a lambda to it will always create an instance of a Function object.


On the other hand, if you use the inline keyword:

inline fun inlined(block: () -> Unit) {
    println("before")
    block()
    println("after")
}

When you call it like this:

inlined {
    println("do something here")
}

No Function instance will be created, instead, the code around the invocation of block inside the inlined function will be copied to the call site, so you'll get something like this in the bytecode:

System.out.println("before");
System.out.println("do something here");
System.out.println("after");

In this case, no new instances are created.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...