Cancellation handling in Swift - Time & Space Complexity
When we handle cancellation in Swift, we want to know how stopping a task early affects how long the program runs.
We ask: How does the program's work change when we cancel tasks?
Analyze the time complexity of the following code snippet.
func performTask(with items: [Int], isCancelled: () -> Bool) {
for item in items {
if isCancelled() {
break
}
// Simulate work
print("Processing \(item)")
}
}
This code processes a list of items but stops early if cancellation is detected.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array items one by one.
- How many times: Up to the number of items, but may stop earlier if cancelled.
Execution grows with the number of items unless cancellation happens early.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10, or fewer if cancelled early |
| 100 | Up to 100, or fewer if cancelled early |
| 1000 | Up to 1000, or fewer if cancelled early |
Pattern observation: The work grows linearly with input size but can be cut short by cancellation.
Time Complexity: O(n)
This means the work grows in a straight line with the number of items, but may be less if we stop early.
[X] Wrong: "Cancellation makes the code always run instantly or in constant time."
[OK] Correct: Cancellation only stops the work early sometimes; if not cancelled, the code still runs through all items.
Understanding how cancellation affects time helps you explain real-world task management and responsiveness in apps.
"What if we changed the cancellation check to happen only every 10 items? How would the time complexity change?"