Passing values vs pointers in Go - Performance Comparison
When we pass values or pointers in Go, it affects how much work the program does.
We want to see how the time to run changes as the data size grows.
Analyze the time complexity of the following code snippet.
func processValue(data [1000]int) {
// Simulate some processing
for _, v := range data {
_ = v * 2
}
}
func processPointer(data *[1000]int) {
// Simulate some processing
for _, v := range *data {
_ = v * 2
}
}
This code shows two functions: one takes a large array by value, the other by pointer, both loop over the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over 1000 elements in the array.
- How many times: Exactly 1000 times for each function call.
- Additional operation for value passing: Copying the entire array once when calling the function.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Copy 10 items + loop 10 times |
| 100 | Copy 100 items + loop 100 times |
| 1000 | Copy 1000 items + loop 1000 times |
Pattern observation: Passing by value adds a copying step that grows with input size, while passing by pointer avoids this copy.
Time Complexity: O(n)
This means the time grows linearly with the size of the data, mainly due to looping and copying when passing by value.
[X] Wrong: "Passing by pointer always makes the code faster regardless of what happens inside the function."
[OK] Correct: Sometimes the function does more work that dominates time, so the cost of copying might be small compared to processing.
Understanding how passing values or pointers affects performance helps you write efficient code and explain your choices clearly.
"What if the array size doubled? How would passing by value vs pointer affect the time complexity then?"