Why pointers are needed in Go - Performance Analysis
We want to understand how using pointers affects the time it takes for a program to run.
Specifically, we ask: does using pointers change how fast or slow our code runs as input grows?
Analyze the time complexity of the following code snippet.
func incrementValue(val int) int {
return val + 1
}
func incrementPointer(val *int) {
*val = *val + 1
}
func main() {
x := 5
x = incrementValue(x)
incrementPointer(&x)
}
This code shows two ways to increase a number: one by passing the value, the other by passing a pointer to the value.
Look for operations that repeat or take time as input changes.
- Primary operation: Simple addition and assignment.
- How many times: Each function runs once here, so constant time.
Since the functions do a fixed number of steps, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 |
| 100 | 2 |
| 1000 | 2 |
Pattern observation: The number of steps stays the same no matter the input size.
Time Complexity: O(1)
This means the time to run these functions stays constant, no matter how big the input is.
[X] Wrong: "Using pointers always makes the program faster because it avoids copying data."
[OK] Correct: For small data like integers, copying is very fast and pointers add extra steps to access memory, so speed difference is often negligible.
Understanding when pointers affect performance helps you write clear and efficient code, a skill valued in many programming tasks.
"What if we changed the function to process a large array by value versus by pointer? How would the time complexity change?"