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
Let me add: When not to use inline
:
If you have a simple function that doesn't accept other functions as an argument, it does not make sense to inline them. IntelliJ will warn you:
Expected performance impact of inlining '...' is insignificant. Inlining works best for functions with parameters of functional types
Even if you have a function "with parameters of functional types", you may encounter the compiler telling you that inlining does not work. Consider this example:
inline fun calculateNoInline(param: Int, operation: IntMapper): Int {
val o = operation //compiler does not like this
return o(param)
}
This code won't compile, yielding the error:
Illegal usage of inline-parameter 'operation' in '...'. Add 'noinline' modifier to the parameter declaration.
The reason is that the compiler is unable to inline this code, particularly the operation
parameter. If operation
is not wrapped in an object (which would be the result of applying inline
), how can it be assigned to a variable at all? In this case, the compiler suggests making the argument noinline
. Having an inline
function with a single noinline
function does not make any sense, don't do that. However, if there are multiple parameters of functional types, consider inlining some of them if required.
So here are some suggested rules:
noinline
for the others.reified
type parameters, which require you to use inline
. Read here.