0
0
Swiftprogramming~5 mins

Await for calling async functions in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Await for calling async functions
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: The for loop calls fetchData for each id.
  • How many times: Once for each element in the ids array.
How Execution Grows With Input

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.

Final Time Complexity

Time Complexity: O(n)

This means the total waiting time grows linearly with the number of async calls.

Common Mistake

[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.

Interview Connect

Understanding how awaiting async calls affects time helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

What if we started all async calls without awaiting inside the loop, then awaited all results together? How would the time complexity change?