Launch coroutine builder in Kotlin - Time & Space Complexity
When we use the launch coroutine builder in Kotlin, it starts a new task that runs alongside other code.
We want to understand how the time it takes to start and run these tasks changes as we start more of them.
Analyze the time complexity of the following code snippet.
import kotlinx.coroutines.*
fun main() = runBlocking {
repeat(5) { i ->
launch {
println("Task $i running")
delay(100L)
}
}
}
This code starts 5 coroutines that each print a message and wait briefly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
repeat(5)loop that launches 5 coroutines. - How many times: Exactly 5 times, once per coroutine started.
As the number of coroutines started increases, the total number of launch operations grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 launches |
| 100 | 100 launches |
| 1000 | 1000 launches |
Pattern observation: The work grows in a straight line as you add more coroutines.
Time Complexity: O(n)
This means the time to start all coroutines grows directly with the number of coroutines you launch.
[X] Wrong: "Starting many coroutines happens instantly and does not add up."
[OK] Correct: Each coroutine launch takes some time, so starting more coroutines adds more work overall.
Understanding how launching many coroutines affects performance helps you write responsive and efficient Kotlin programs.
"What if we replaced launch with async? How would the time complexity change?"