0
0
Swiftprogramming~5 mins

Defer statement for cleanup in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Defer statement for cleanup
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each item causes two print actions: one normal and one deferred cleanup.

Input Size (n)Approx. Operations
1020 prints
100200 prints
10002000 prints

Pattern observation: The total work doubles but still grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items, even with defer cleanup.

Common Mistake

[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.

Interview Connect

Understanding how defer affects time helps you explain code cleanup clearly and shows you can think about performance even in simple-looking code.

Self-Check

What if the defer block contained a loop over all items instead of just a print? How would the time complexity change?