0
0
Swiftprogramming~5 mins

Task for launching concurrent work in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Task for launching concurrent work
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each new task adds one more unit of work to start, but tasks run at the same time.

Input Size (n)Approx. Operations
1010 tasks started quickly
100100 tasks started quickly
10001000 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.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding how launching concurrent tasks scales helps you explain how programs handle many jobs at once, a useful skill in real projects and interviews.

Self-Check

"What if each task waited for the previous one to finish before starting? How would the time complexity change?"