when to use an inline function in Kotlin?

后端 未结 5 359
借酒劲吻你
借酒劲吻你 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:37

    The most important case when we use the inline modifier is when we define util-like functions with parameter functions. Collection or string processing (like filter, map or joinToString) or just standalone functions are a perfect example.

    This is why the inline modifier is mostly an important optimization for library developers. They should know how it works and what are its improvements and costs. We should use the inline modifier in our projects when we define our own util functions with function type parameters.

    If we don’t have function type parameter, reified type parameter, and we don’t need non-local return, then we most likely shouldn’t use the inline modifier. This is why we will have a warning on Android Studio or IDEA IntelliJ.

    Also, there is a code size problem. Inlining a large function could dramatically increase the size of the bytecode because it's copied to every call site. In such cases, you can refactor the function and extract code to regular functions.

提交回复
热议问题