0
0
Goprogramming~5 mins

Why defer is used in Go - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why defer is used
O(n)
Understanding Time Complexity

We want to understand how using defer affects the time it takes for a Go program to run.

Specifically, we ask: Does defer add extra work as the program runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func process(items []int) {
    for _, item := range items {
        defer cleanup(item)
        // do some work with item
    }
}

func cleanup(i int) {
    // cleanup logic here
}
    

This code defers cleanup calls for each item in a list, running them after process finishes.

Identify Repeating Operations

Look for loops or repeated actions that take time.

  • Primary operation: Loop over items and call defer for each.
  • How many times: Once per item in the list.
How Execution Grows With Input

Each item adds one deferred call, so the work to set up defers grows with the number of items.

Input Size (n)Approx. Operations
1010 defer calls set up
100100 defer calls set up
10001000 defer calls set up

Pattern observation: The number of defer setups grows directly with input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to set up all deferred calls grows linearly as the input list gets bigger.

Common Mistake

[X] Wrong: "Using defer does not add any extra time cost because it just schedules work for later."

[OK] Correct: Each defer call adds a small overhead immediately to remember the deferred function, so more defers mean more work during the loop.

Interview Connect

Understanding how defer affects time helps you write clear and efficient Go code, a skill valued in many coding challenges and real projects.

Self-Check

"What if we moved the defer call outside the loop? How would the time complexity change?"