Why modern concurrency matters in Swift - Performance Analysis
Modern concurrency helps programs do many things at once. This affects how long tasks take when many run together.
We want to see how adding concurrency changes the work done as tasks grow.
Analyze the time complexity of the following code snippet.
func fetchDataConcurrently(urls: [String]) async {
await withTaskGroup(of: Void.self) { group in
for url in urls {
group.addTask {
await fetch(url: url)
}
}
}
}
func fetch(url: String) async {
// Simulate network fetch
try? await Task.sleep(nanoseconds: 1_000_000_000)
}
This code fetches data from many URLs at the same time using concurrency.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over each URL to start a concurrent fetch task.
- How many times: Once per URL in the input list.
Each URL starts a task that runs at the same time, so total time depends on the longest single fetch, not all combined.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 tasks started, total time about 1 fetch duration |
| 100 | 100 tasks started, total time about 1 fetch duration |
| 1000 | 1000 tasks started, total time about 1 fetch duration |
Pattern observation: Time grows very little with more tasks because they run at the same time.
Time Complexity: O(1)
This means the total time stays about the same no matter how many tasks run, thanks to concurrency.
[X] Wrong: "Running many tasks at once will take much longer because there are more tasks."
[OK] Correct: Because tasks run at the same time, total time depends on the slowest task, not the number of tasks.
Understanding how concurrency changes time helps you explain how apps stay fast even with many things happening together.
"What if the fetch tasks had to run one after another instead of concurrently? How would the time complexity change?"