0
0
Swiftprogramming~5 mins

Structured concurrency model in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Structured concurrency model
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code changes when using Swift's structured concurrency model.

Specifically, we ask: how does adding more concurrent tasks affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following Swift code using structured concurrency.


func fetchData(n: Int) async {
  await withTaskGroup(of: Void.self) { group in
    for i in 1...n {
      group.addTask {
        await process(i)
      }
    }
  }
}

func process(_ value: Int) async {
  // Simulate work
  try? await Task.sleep(nanoseconds: 1_000_000)
}
    

This code runs n tasks concurrently, each doing some work asynchronously.

Identify Repeating Operations

Look for repeated actions that affect time.

  • Primary operation: launching and running n concurrent tasks.
  • How many times: exactly n times, once per task.
How Execution Grows With Input

As n grows, the number of tasks grows linearly.

Input Size (n)Approx. Operations
1010 tasks launched and processed
100100 tasks launched and processed
10001000 tasks launched and processed

Pattern observation: The total work grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows in direct proportion to the number of tasks you run.

Common Mistake

[X] Wrong: "Because tasks run concurrently, adding more tasks doesn't increase total time."

[OK] Correct: Even if tasks run at the same time, the system still needs to start and manage each task, so total work grows with the number of tasks.

Interview Connect

Understanding how concurrency affects time helps you explain how programs scale and manage work efficiently.

Self-Check

What if we changed from launching all tasks concurrently to launching them one after another? How would the time complexity change?