Coroutine context and dispatchers in Kotlin - Time & Space Complexity
When using coroutines in Kotlin, it's important to understand how the work is scheduled and run. This affects how long your program takes as you add more tasks.
We want to see how the choice of coroutine context and dispatcher affects the time it takes to run multiple coroutines.
Analyze the time complexity of the following code snippet.
import kotlinx.coroutines.*
fun main() = runBlocking {
repeat(1000) { i ->
launch(Dispatchers.Default) {
delay(100L)
println("Task $i done")
}
}
}
This code launches 1000 coroutines on the Default dispatcher, each waiting 100 milliseconds before printing a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Launching 1000 coroutines with a delay inside each.
- How many times: The launch block runs 1000 times, each scheduling a coroutine.
As the number of coroutines increases, the total work grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 coroutines launched, each delayed and printed |
| 100 | 100 coroutines launched, more scheduling and delays |
| 1000 | 1000 coroutines launched, more overhead but still linear growth |
Pattern observation: The time to launch and run all coroutines grows roughly linearly with the number of coroutines.
Time Complexity: O(n)
This means if you double the number of coroutines, the total work and time roughly double too.
[X] Wrong: "Launching many coroutines always runs tasks in parallel instantly, so time stays the same no matter how many coroutines."
[OK] Correct: Even though coroutines are lightweight, the dispatcher schedules them on limited threads, so more coroutines mean more total work and longer total time.
Understanding how coroutine dispatchers affect execution time helps you write efficient asynchronous code. This skill shows you can reason about how your program scales with more tasks.
What if we changed the dispatcher from Dispatchers.Default to Dispatchers.IO? How would the time complexity change?