Defer statement for cleanup in Swift - Time & Space Complexity
We want to understand how using a defer statement affects the time it takes for a program to run.
Specifically, does adding cleanup code with defer change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
func processItems(_ items: [Int]) {
for item in items {
defer {
print("Cleanup for \(item)")
}
print(item)
}
}
This code prints each item in a list and then uses defer to print a cleanup message after each item.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each item in the array.
- How many times: Once for every item in the list.
Each item causes two print actions: one normal and one deferred cleanup.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 prints |
| 100 | 200 prints |
| 1000 | 2000 prints |
Pattern observation: The total work doubles but still grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items, even with defer cleanup.
[X] Wrong: "Defer adds extra loops or makes the program slower in a way that changes the overall time complexity."
[OK] Correct: Defer only adds a small fixed action after each loop iteration, so it grows with the loop and does not add nested or repeated loops.
Understanding how defer affects time helps you explain code cleanup clearly and shows you can think about performance even in simple-looking code.
What if the defer block contained a loop over all items instead of just a print? How would the time complexity change?