Performance of Suspending Functions
Explore the internal mechanics of Kotlin suspending functions, including how continuations replace call stacks during suspension and resumption. Understand the performance implications and why suspending functions are efficient despite the complexity of their state management.
We'll cover the following...
Call stack
When function a calls the function b, the virtual machine needs to store the state of a somewhere and the address where execution should return once b finishes. For storing this, we'll use a structure called a call stack. The call stack has limited space. When we've used it all, a StackOverflowError occurs. The problem is that when we suspend, we free a thread, and as a result, we clear our call stack. Therefore, the call stack is not useful when we resume.
Instead, the continuations serve as a call stack. Each continuation keeps the state where we suspended (as a label), the function’s local variables and parameters (as fields), and the reference to the continuation of the function called this function. One continuation references another, which references another, etc. As a result, our continuation is like a huge onion. It keeps everything that is generally on the call stack. Take a look at the ...