Pointer receivers in Go - Time & Space Complexity
When using pointer receivers in Go methods, it's important to understand how this choice affects the speed of your program.
We want to see how the program's work changes as the input size grows when pointer receivers are involved.
Analyze the time complexity of the following Go code using pointer receivers.
type Counter struct {
value int
}
func (c *Counter) Increment(n int) {
for i := 0; i < n; i++ {
c.value++
}
}
This code defines a Counter with a pointer receiver method that increments its value n times.
Look at what repeats in the code.
- Primary operation: The for loop that increments the counter value.
- How many times: Exactly n times, where n is the input to Increment.
As n grows, the number of increments grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the Increment method grows linearly with the input size n.
[X] Wrong: "Using a pointer receiver makes the method run faster regardless of input size."
[OK] Correct: Pointer receivers avoid copying the whole struct, but the loop inside still runs n times, so the time depends on n, not just the receiver type.
Understanding how pointer receivers affect method performance helps you write clear and efficient Go code, a skill that shows you know how to manage resources well.
"What if the Increment method used a value receiver instead of a pointer receiver? How would the time complexity change?"