0
0
Swiftprogramming~5 mins

Task groups for parallel execution in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Task groups for parallel execution
O(T)
Understanding Time Complexity

When using task groups for parallel execution, we want to know how the total work grows as we add more tasks.

We ask: How does running many tasks at once affect the time it takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func fetchAllData(n: Int) async {
  await withTaskGroup(of: String.self) { group in
    for i in 1...n {
      group.addTask {
        await fetchData(id: i)
      }
    }
    for await result in group {
      print(result)
    }
  }
}

func fetchData(id: Int) async -> String {
  // Simulate network call
  return "Data \(id)"
}
    

This code runs n tasks in parallel to fetch data, then waits for all to finish.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding and running n tasks in the task group.
  • How many times: The loop runs n times, creating n parallel tasks.
How Execution Grows With Input

As n grows, the number of tasks grows linearly, but tasks run at the same time.

Input Size (n)Approx. Operations
1010 tasks run in parallel
100100 tasks run in parallel
10001000 tasks run in parallel

Pattern observation: The number of tasks grows with n, but total time depends on the longest single task, not the sum.

Final Time Complexity

Time Complexity: O(T)

This means the total time to complete all tasks stays roughly the same as n grows, assuming tasks run truly in parallel and each task takes time T.

Common Mistake

[X] Wrong: "More tasks always mean more total time because they add up."

[OK] Correct: When tasks run in parallel, total time depends on the slowest task, not the number of tasks.

Interview Connect

Understanding how parallel tasks affect time helps you explain real-world app performance and shows you can think about efficient code.

Self-Check

"What if tasks run sequentially instead of in parallel? How would the time complexity change?"