Sendable protocol for thread safety in Swift - Time & Space Complexity
When using the Sendable protocol in Swift, we want to understand how checking thread safety affects program speed.
We ask: how does the time to verify or use Sendable scale as data size or complexity grows?
Analyze the time complexity of the following code snippet.
struct DataItem: Sendable {
let value: Int
}
func processItems(_ items: [DataItem]) async {
await withTaskGroup(of: Void.self) { group in
for item in items {
group.addTask {
print(item.value)
}
}
}
}
This code processes an array of Sendable items concurrently, ensuring thread safety.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the array to create a concurrent task.
- How many times: Once for each item in the input array.
Each item causes one task to be created and run concurrently.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 tasks created and run |
| 100 | 100 tasks created and run |
| 1000 | 1000 tasks created and run |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to process grows linearly as the number of items increases.
[X] Wrong: "Using Sendable makes the program run instantly regardless of data size."
[OK] Correct: Sendable ensures safety but does not remove the need to process each item, so time still grows with input size.
Understanding how thread safety protocols like Sendable affect performance helps you write safe and efficient concurrent code.
What if we changed the array to a nested array of items? How would the time complexity change?