0
0
Kotlinprogramming~5 mins

Coroutines vs threads mental model in Kotlin - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Coroutines vs threads mental model
O(n)
Understanding Time Complexity

When working with coroutines and threads in Kotlin, it is important to understand how their execution costs grow as we increase workload.

We want to see how the time taken changes when we run many tasks using coroutines versus threads.

Scenario Under Consideration

Analyze the time complexity of launching multiple tasks using threads and coroutines.


fun runThreads(n: Int) {
    repeat(n) {
        Thread {
            // some work
        }.start()
    }
}

suspend fun runCoroutines(n: Int) {
    repeat(n) {
        kotlinx.coroutines.GlobalScope.launch {
            // some work
        }
    }
}
    

This code runs n tasks either by creating n threads or launching n coroutines.

Identify Repeating Operations

Look at what repeats as input size grows.

  • Primary operation: Creating and running n tasks (threads or coroutines).
  • How many times: Exactly n times, once per task.
How Execution Grows With Input

As we increase n, the number of tasks grows linearly.

Input Size (n)Approx. Operations
1010 tasks created and run
100100 tasks created and run
10001000 tasks created and run

Pattern observation: The work grows directly with the number of tasks.

Final Time Complexity

Time Complexity: O(n)

This means the time to start and run all tasks grows in a straight line as we add more tasks.

Common Mistake

[X] Wrong: "Coroutines always run faster than threads because they are lightweight."

[OK] Correct: While coroutines use fewer resources, the total time depends on the work done and how tasks are scheduled, not just on their lightweight nature.

Interview Connect

Understanding how coroutines and threads scale helps you explain efficient multitasking in Kotlin, a skill useful in many programming situations.

Self-Check

What if we changed the tasks to do heavy CPU work instead of light work? How would the time complexity change?