Why methods are used in Go - Performance Analysis
We want to understand how using methods affects the time it takes for a program to run.
Specifically, we ask: Does calling a method change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
package main
import "fmt"
type Counter struct {
count int
}
func (c *Counter) Increment() {
c.count++
}
func main() {
c := Counter{}
for i := 0; i < 1000; i++ {
c.Increment()
}
fmt.Println(c.count)
}
This code defines a method to increase a count and calls it many times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
Incrementmethod inside a loop. - How many times: 1000 times, once per loop iteration.
Each time the input (loop count) grows, the number of method calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input gets bigger.
[X] Wrong: "Using methods always makes the program slower in a big way."
[OK] Correct: Calling a method is just like running a small piece of code; it doesn't add extra loops or big work by itself.
Understanding how methods affect time helps you explain your code clearly and shows you know how programs grow with input size.
"What if the Increment method itself had a loop inside? How would the time complexity change?"