Search code examples
kotlinsuspendkotlinx.coroutines

kotlin coroutines. Difference between launch{ fun} and launch {suspend fun}


Is there any difference in execution between?

launch {
    function1()
}
fun function1(){
    DoSomething...
}

And

launch {
   function2()
}
suspend fun function2(){
   DoSomething...
}

Solution

  • Yes, there is.

    Semantically, a call to a suspending function may suspend the execution, which may be resumed at some point later (or never), possibly in a different context (e.g. another thread).

    To ensure this, the compiler handles calls to a suspending function in a special way: it produces the code that saves the current local variables into a Continuation instance and passes it to the suspending function, and there's also a resumption point in the bytecode after the call, to which the execution will jump, load the local variables and run on (with a corner case of tail calls).

    A call to a non-suspending function is compiled to much simpler bytecode, the same to normally calling a function outside a suspending function body.

    You can find details about Kotlin coroutines design and implementation here: Coroutines for Kotlin

    You can also inspect the resulting compiled bytecode to see the difference: Kotlin Bytecode - How to analyze in IntelliJ IDEA?