Task groups for parallel execution in Swift - Time & Space 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?
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 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.
As n grows, the number of tasks grows linearly, but tasks run at the same time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 tasks run in parallel |
| 100 | 100 tasks run in parallel |
| 1000 | 1000 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.
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.
[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.
Understanding how parallel tasks affect time helps you explain real-world app performance and shows you can think about efficient code.
"What if tasks run sequentially instead of in parallel? How would the time complexity change?"