Common pointer use cases in Go - Time & Space Complexity
When using pointers in Go, it's important to understand how they affect the speed of your program.
We want to see how the program's running time changes when pointers are used in common ways.
Analyze the time complexity of the following code snippet.
package main
func incrementAll(nums []*int) {
for _, p := range nums {
*p = *p + 1
}
}
This code takes a slice of pointers to integers and adds 1 to each integer by using the pointers.
- Primary operation: Looping through the slice of pointers and dereferencing each pointer to update the value.
- How many times: Once for each element in the slice (n times if the slice has n elements).
As the number of pointers in the slice grows, the time to update all values grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 updates |
| 100 | 100 updates |
| 1000 | 1000 updates |
Pattern observation: The time grows directly with the number of elements; doubling the slice doubles the work.
Time Complexity: O(n)
This means the time to complete the task grows in direct proportion to the number of pointers you have.
[X] Wrong: "Using pointers makes the loop run faster because it avoids copying values."
[OK] Correct: While pointers avoid copying data, the loop still visits every element, so the total time still grows with the number of elements.
Understanding how pointers affect time helps you explain your code choices clearly and shows you know how your program scales with data size.
"What if we changed the slice of pointers to a slice of values? How would the time complexity change?"