Inlining Functions with Lambdas
Lambdas are elegant, and it’s convenient to pass functions to functions, but there’s a catch—performance. Kotlin provides the inline
keyword to eliminate the call overhead in order to improve performance, to provide non-local control flow such as a return from within forEach()
, and to pass reified type parameters as we saw in Reified Type Parameters.
Before we delve into ways to improve performance of functions that use lambdas, let’s set some context. Every higher-order function we write doesn’t need the solutions we’ll see in this section. A good amount of code we write will enjoy a reasonable performance and need nothing special. But in some situations—such as when a higher-order function contains a loop and excessively calls a lambda expression from within the loop, for example—the overhead of calling the higher-order function and the lambdas within it may be measurable. In that case, and only in that case, measure the performance first, and then consider these added complexities to improve the performance where necessary.
No inline optimization by default
To learn about inline
, let’s create an invokeTwo()
function that takes an Int
and two lambdas. It also returns a lambda. We’ll modify this function a few times in this section, but the following is a good starting point without any inline
:
Get hands-on with 1200+ tech skills courses.