Method call behavior in Go - Time & Space Complexity
When we call a method in Go, it runs some code. We want to know how the time it takes changes as the input grows.
How does calling a method affect the total work done by the program?
Analyze the time complexity of the following code snippet.
package main
import "fmt"
type Counter struct {
count int
}
func (c *Counter) Increment(n int) {
for i := 0; i < n; i++ {
c.count++
}
}
func main() {
c := Counter{}
c.Increment(100)
fmt.Println(c.count)
}
This code defines a method Increment that adds 1 to count n times. We call it with n = 100.
- Primary operation: The for loop inside the Increment method that runs c.count++ repeatedly.
- How many times: The loop runs exactly n times, where n is the input to Increment.
As n grows, the number of times we add to count 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. Double n, double the work.
Time Complexity: O(n)
This means the time to run the method grows in a straight line with the input size n.
[X] Wrong: "Calling a method always takes the same time no matter what."
[OK] Correct: The method here has a loop that runs n times, so bigger n means more work and more time.
Understanding how method calls affect time helps you explain your code clearly and shows you know what happens inside your functions.
"What if the Increment method called another method inside the loop? How would that change the time complexity?"