When to avoid inline functions in Kotlin?

In Kotlin, an inline function is a function that is expanded at the call site, rather than being executed as a separate function call. This can improve performance in certain cases, especially when the function is called frequently and has a small body. To declare a function as inline, you use the “inline” keyword before the function declaration.

If you inline every function in Kotlin, you may be doing more harm than good. Let’s understand why

An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.

Assume we have a function that just prints the text “Hello world!”

If you come from a C/C++ background, you could be tempted to inline this function since we know that the compiler will inline the code block to the caller site and we’ll gain performance as shown below.

inline void printString()
{
	std::cout << "Hello world!";
}

But if you try to do the same in Kotlin,

inline fun printString() {
	println("Hello world!")
}

Kotlin compiler will warn you that “Expected performance impact of inlining ‘…’ is insignificant. Inlining works best for functions with parameters of functional types.”

But why is that? Why is the Kotlin compiler shouting at you if it works great in C/C++?

This is due to the fact that Kotlin is JVM-based and we have the concept of bytecode.

When you inline a function, the resultant bytecode contains some additional code (bloat). So, if you explicitly inline a short function, you’re incurring that unnecessary expense.

There is no need to inline a short, frequently called function because the JVM Just-in-Time (JIT) compiler will most likely do it for you when it considers it suitable.

That is why it is recommended to only inline functions that use lambda parameter (higher order function) because we are inlining the entire function argument to the call site, which is beneficial for performance.

Share with your friends

Leave a Reply

Your email address will not be published. Required fields are marked *