0
0
Goprogramming~5 mins

Defer execution order in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Defer execution order
O(n)
Understanding Time Complexity

When using defer in Go, it's important to know how the order of deferred calls affects program steps.

We want to see how the number of deferred calls impacts the total work done when the function ends.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

func example(n int) {
    for i := 0; i < n; i++ {
        defer func(x int) {
            println(x)
        }(i)
    }
}

This code defers printing numbers from 0 to n-1, storing each deferred call during the loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Loop runs n times, each time adding one deferred function call.
  • How many times: Exactly n deferred calls are stacked.
How Execution Grows With Input

Each loop adds one deferred call, and at the end, all deferred calls run in reverse order.

Input Size (n)Approx. Operations
1010 deferred calls added and then 10 executed
100100 deferred calls added and then 100 executed
10001000 deferred calls added and then 1000 executed

Pattern observation: The total work grows linearly with n because each deferred call is stored and later executed once.

Final Time Complexity

Time Complexity: O(n)

This means the total steps grow in a straight line as the number of deferred calls increases.

Common Mistake

[X] Wrong: "Deferred calls run immediately or only once at the end without extra cost."

[OK] Correct: Deferred calls are stacked during execution and all run later, so the total work includes both stacking and running each deferred call.

Interview Connect

Understanding how defer stacks calls and affects execution helps you reason about function cleanup and resource management in real programs.

Self-Check

"What if we replaced defer with immediate function calls inside the loop? How would the time complexity change?"