Why defer is used in Go - Performance Analysis
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?
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.
Look for loops or repeated actions that take time.
- Primary operation: Loop over
itemsand calldeferfor each. - How many times: Once per item in the list.
Each item adds one deferred call, so the work to set up defers grows with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 defer calls set up |
| 100 | 100 defer calls set up |
| 1000 | 1000 defer calls set up |
Pattern observation: The number of defer setups grows directly with input size.
Time Complexity: O(n)
This means the time to set up all deferred calls grows linearly as the input list gets bigger.
[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.
Understanding how defer affects time helps you write clear and efficient Go code, a skill valued in many coding challenges and real projects.
"What if we moved the defer call outside the loop? How would the time complexity change?"