What is the difference between crossinline and noinline in Kotlin? -
this code compiles warning (insignificant performance impact):
inline fun test(noinline f: () -> unit) { thread(block = f) }
this code does not compile (illegal usage of inline-parameter):
inline fun test(crossinline f: () -> unit) { thread(block = f) }
this code compiles warning (insignificant performance impact):
inline fun test(noinline f: () -> unit) { thread { f() } }
this code compiles no warning or error:
inline fun test(crossinline f: () -> unit) { thread { f() } }
here questions:
- how come (2) not compile (4) does?
- what difference between
noinline
,crossinline
? - if (3) not generates no performance improvements, why (4) do?
from inline functions reference:
note inline functions may call lambdas passed them parameters not directly function body, execution context, such local object or nested function. in such cases, non-local control flow not allowed in lambdas. indicate that, lambda parameter needs marked crossinline modifier
hence, example 2. doesn't compile, since crossinline
enforces local control flow, , expression block = f
violates that. example 1 compiles, since noinline
doesn't require such behavior (obviously, since it's ordinary function parameter).
examples 1 , 3 not generate performance improvements, since lambda parameter marked noinline
, rendering inline
modifier of function useless , redundant - compiler inline something, has been marked not inlined.
consider 2 functions, a , b
a
inline fun test(noinline f: () -> unit) { thread { f() } }
b
fun test(f: () -> unit) { thread { f() } }
function a behaves function b in sense parameter f
not inlined (the b function doesn't inline body of test
whereas in a function, body: thread { f() }
still gets inlined).
now, not true in example 4, since crossinline f: () -> unit
parameter can inlined, cannot violate aforementioned non-local control flow rule (like assigning new value global variable). , if can inlined, compiler assumes performance improvements , not warn in example 3.
Comments
Post a Comment