Await for calling async functions in Swift - Time & Space Complexity
When we use await to call async functions, we want to know how the waiting affects the program's speed.
We ask: How does the total time grow when we wait for multiple async calls?
Analyze the time complexity of the following code snippet.
func fetchData(id: Int) async -> String {
// Simulate network delay
try? await Task.sleep(nanoseconds: 1_000_000_000) // 1 second
return "Data \(id)"
}
func loadAllData(ids: [Int]) async -> [String] {
var results = [String]()
for id in ids {
let data = await fetchData(id: id)
results.append(data)
}
return results
}
This code fetches data for each id one by one, waiting for each async call to finish before starting the next.
- Primary operation: The
forloop callsfetchDatafor each id. - How many times: Once for each element in the
idsarray.
Each async call waits about 1 second before returning. Since calls happen one after another, total time adds up.
| Input Size (n) | Approx. Operations (seconds) |
|---|---|
| 10 | ~10 seconds |
| 100 | ~100 seconds |
| 1000 | ~1000 seconds |
Pattern observation: Total time grows directly with the number of calls, because each waits for the previous to finish.
Time Complexity: O(n)
This means the total waiting time grows linearly with the number of async calls.
[X] Wrong: "Using await inside a loop runs all async calls at the same time, so total time stays the same no matter how many calls."
[OK] Correct: Await inside a loop waits for each call to finish before starting the next, so calls run one after another, increasing total time.
Understanding how awaiting async calls affects time helps you write efficient code and explain your reasoning clearly in interviews.
What if we started all async calls without awaiting inside the loop, then awaited all results together? How would the time complexity change?