when to use an inline function in Kotlin?

后端 未结 5 357
借酒劲吻你
借酒劲吻你 2020-12-04 05:50

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         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 06:14

    Let me add: When not to use inline:

    1. 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

    2. 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:

    • You can inline when all functional type parameters are called directly or passed to other inline function
    • You should inline when ^ is the case.
    • You cannot inline when function parameter is being assigned to a variable inside the function
    • You should consider inlining if at least one of your functional type parameters can be inlined, use noinline for the others.
    • You should not inline huge functions, think about generated byte code. It will be copied to all places the function is called from.
    • Another use case is reified type parameters, which require you to use inline. Read here.

提交回复
热议问题