Task for launching concurrent work in Swift - Time & Space Complexity
When we launch work to run at the same time using tasks, it's important to see how the time needed changes as we add more tasks.
We want to know how the total work grows when we start many tasks concurrently.
Analyze the time complexity of the following code snippet.
func launchTasks(count: Int) async {
for i in 1...count {
Task {
print("Task \(i) started")
// Simulate some work
try? await Task.sleep(nanoseconds: 1_000_000)
print("Task \(i) finished")
}
}
}
This code launches a number of tasks concurrently, each doing a small amount of work.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that creates and starts each Task.
- How many times: Exactly once for each task, so count times.
Each new task adds one more unit of work to start, but tasks run at the same time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 tasks started quickly |
| 100 | 100 tasks started quickly |
| 1000 | 1000 tasks started quickly |
Pattern observation: The number of task launches grows directly with input size, but tasks run concurrently, so total time does not grow much with more tasks.
Time Complexity: O(n)
This means the work to start tasks grows linearly with the number of tasks, but the tasks themselves run at the same time.
[X] Wrong: "Starting many tasks means the total time will be n times longer."
[OK] Correct: Tasks run concurrently, so starting more tasks adds work to launch them, but they mostly run at the same time, not one after another.
Understanding how launching concurrent tasks scales helps you explain how programs handle many jobs at once, a useful skill in real projects and interviews.
"What if each task waited for the previous one to finish before starting? How would the time complexity change?"