I'm reading `Kotlin Coroutines deep dive` by `Marc...
# coroutines
I'm reading
Kotlin Coroutines deep dive
Marcin Moskala
. In the part of
understanding Kotlin Coroutine
of the book(specifically,
How does suspension work?
), I read this code below.
Copy code
suspend fun main() {
  suspendCoroutine<Unit> { continuation ->
// Before
// After
Notice that “After” in the example above is printed because we call
resume in suspendCoroutine. This statement is true, but I need to clarify. You might imagine
that here we suspend and immediately resume. This is a good intuition, but the truth is that there is an optimization that prevents a suspension if resuming is immediate.
Speaking of the
, in this case, Does it mean that "There is no suspension point in the Coroutine. So, there is no need to be suspended. That's why the compiler optimizes."?? For instances, 1)
Copy code
suspend fun getUsers(): List<User> {
   // no asynchronous work and suspension point here
   // ....
  return users
in the code above, the IDE informs me that I don't need to use "suspend"(Redundant 'suspend' modifier). So, it also would be an optimazation. 2)
Copy code
suspend fun getUsers(): List<User> {
  suspendCoroutine<Unit> { continuation -> // this code line is definitely a suspention point.
  // list sorting or something but not asynchronous work.
 return users
in the code above, it's almost same code of the example of the book. but i wonder how the compiler optimizes the code under the hood. and I wonder if there are any other optimizations for
. i hope someone tells me about it.
Hi there! I'm reading the same book now, and it's a great one 🙌🏻 I'm on the phone and cab't answer with specifics, but I recommend you to take a look at the Java equivalent code. This equivalent code is generated by following this steps: • The Kotlin compiler compiles the code (in case of the JVM target, the output is JVM bytecode) • The IDE decompiler tool gets an equivalent Java version from that JVM bytecode This means that the generated JVM bytecode will have applied all the compiler performance improvements
Thank you Xoán González! I'll read it!
Compiler-wise, when there are no suspension points in the function body, there’s no need to do any transformation to the coroutine state machine. Also, deep down, a suspension is always (I think) eventually a call to
. Note the
. That means this call will either return some value immediately, or
token. If this function never returns the suspended token, code transformation into a state machine would also not be needed, but I’m not sure if compiler is that smart to detect this case
That's interesting and makes sense. Thank you Patrick!