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?"
Practice
async and await in Swift?Solution
Step 1: Understand what concurrency means
Concurrency means doing multiple tasks at once, which helps apps stay responsive.Step 2: Connect concurrency with
These keywords let Swift run tasks without waiting and freezing the app.asyncandawaitFinal Answer:
It allows your app to do many tasks at the same time without freezing. -> Option BQuick Check:
Modern concurrency = smooth multitasking [OK]
- Thinking concurrency slows the app down
- Confusing concurrency with more memory use
- Believing async/await removes functions
Solution
Step 1: Recall Swift async function syntax
In Swift,asynccomes after the function parentheses.Step 2: Check each option's syntax
Only func fetchData() async -> String placesasynccorrectly after the parentheses.Final Answer:
func fetchData() async -> String -> Option AQuick Check:
async keyword after () = correct syntax [OK]
- Placing async before func
- Inserting async inside parameter list
- Putting async before return type
func fetchNumber() async -> Int {
return 10
}
Task {
let number = await fetchNumber()
print(number)
}Solution
Step 1: Understand async function behavior
The functionfetchNumber()returns 10 asynchronously.Step 2: Check how Task and await work
The Task runs the async code, andawaitwaits for the result before printing.Final Answer:
10 -> Option DQuick Check:
await fetchNumber() returns 10 [OK]
- Forgetting to use await
- Expecting print before result is ready
- Thinking async functions run instantly
func loadData() async -> String {
return "Data"
}
func printData() {
let result = await loadData()
print(result)
}Solution
Step 1: Check where await is used
The functionprintData()usesawaitinside its body.Step 2: Confirm async requirement for await
Any function usingawaitmust be markedasync.Final Answer:
Missing async keyword in printData function declaration -> Option CQuick Check:
await requires async function [OK]
- Not marking function async when using await
- Thinking await can be used in normal functions
- Confusing async with return type
Solution
Step 1: Understand sequential vs concurrent calls
Calling await one after another waits for the first to finish before starting the second.Step 2: Use async let for concurrency
Usingasync letstarts both tasks simultaneously, improving speed.Final Answer:
Use async let to start both fetchUser() and fetchPosts() at the same time, then await both results. -> Option AQuick Check:
async let = concurrent tasks [OK]
- Awaiting tasks one by one causing delay
- Mixing synchronous and asynchronous calls incorrectly
- Using old concurrency methods instead of async/await
Ready to prove it?
Pass the test and this pattern moves unknown
