Suspend functions concept in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run suspend functions changes as the input grows.
How does the program's work increase when using suspend functions with more data?
Analyze the time complexity of the following code snippet.
suspend fun fetchData(ids: List<Int>): List<String> {
val results = mutableListOf<String>()
for (id in ids) {
val data = fetchFromNetwork(id) // suspend function
results.add(data)
}
return results
}
suspend fun fetchFromNetwork(id: Int): String {
// Simulate network delay
kotlinx.coroutines.delay(100)
return "Data for $id"
}
This code fetches data for each id in a list by calling a suspend function that simulates a network delay.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over the list of ids and calling the suspend function fetchFromNetwork for each.
- How many times: Once for each id in the input list.
Each new id adds one more network call, so the total work grows directly with the number of ids.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 network calls |
| 100 | 100 network calls |
| 1000 | 1000 network calls |
Pattern observation: The work grows in a straight line as the input size increases.
Time Complexity: O(n)
This means the time to finish grows directly in proportion to the number of items we process.
[X] Wrong: "Suspend functions run all at once, so time stays the same no matter how many items."
[OK] Correct: Each suspend call waits for its own delay before continuing, so doing many calls one after another adds up time.
Understanding how suspend functions affect time helps you explain how asynchronous code scales in real apps.
"What if we changed the for-loop to run all fetchFromNetwork calls concurrently? How would the time complexity change?"