iTranslated by AI
When to Use Pointers in Go
This article is for the 22nd day of the Go 2 Advent Calendar 2020.
Go has the concept of pointers.
Passing variables by pointer is efficient because you don't need to copy values; you just pass the address. However, in Go, overusing pointers can put a load on the garbage collector, potentially consuming a lot of CPU time.
For example, let's prepare a structure S, and create functions that return it by copy and by pointer, respectively:
type S struct {
a, b, c int64
d, e, f string
g, h, i float64
}
func byCopy() S {
return S{
a: 1, b: 1, c: 1,
e: "foo", f: "foo",
g: 1.0, h: 1.0, i: 1.0,
}
}
func byPointer() *S {
return &S{
a: 1, b: 1, c: 1,
e: "foo", f: "foo",
g: 1.0, h: 1.0, i: 1.0,
}
}
If you write the following code to benchmark the functions prepared above:
func BenchmarkStack(b *testing.B) {
var s S
f, err := os.Create("stack.out")
if err != nil {
panic(err)
}
defer f.Close()
err = trace.Start(f)
if err != nil {
panic(err)
}
for i := 0; i < b.N; i++ {
s = byCopy()
}
trace.Stop()
b.StopTimer()
_ = fmt.Sprintf("%v", s.a)
}
func BenchmarkMemoryHeap(b *testing.B) {
var s *S
f, err := os.Create("heap.out")
if err != nil {
panic(err)
}
defer f.Close()
err = trace.Start(f)
if err != nil {
panic(err)
}
for i := 0; i < b.N; i++ {
s = byPointer()
}
trace.Stop()
b.StopTimer()
_ = fmt.Sprintf("%v", s.a)
}
The following results are obtained (go version go1.15.6 linux/amd64). The function that copies performs better.
BenchmarkStack 127888153 9.41 ns/op 0 B/op 0 allocs/op
BenchmarkMemoryHeap 16394270 68.2 ns/op 96 B/op 1 allocs/op
When to use pointers
So, in what situations should pointers be used?
When you need to modify arguments or receivers within a function
When you need to modify arguments or receivers inside a function, the targets to be modified must be passed as pointers.
type S struct { value string }
func (s S) SetA (v string) {
s.value = v
}
func (s *S) SetB (v string) {
s.value = v
}
func main() {
var s S
s.SetA("a")
fmt.Println(s.value) // s remains the zero value
s.SetB("b")
fmt.Println(s.value) // b
}
Conversely, for functions that do not modify the receiver, it is preferable to use value receivers because it makes it explicit in the signature alone that "this function does not modify the receiver," which is also better for readability.
When the data you want to avoid copying is used as an argument or receiver
For structures that cause problems if copied, such as os.File or sync.Mutex, you should use pointers to ensure they are not copied.
// os.Open returns a pointer to a File type
func Open(name string) (file *File, err error) {
return OpenFile(name, O_RDONLY, 0)
}
When handling large structures or arrays
It is more efficient to use pointers when handling large structures or arrays. Conversely, for primitive types like int or string, or structures without many fields, the cost of copying is negligible. In fact, using pointers for those cases can be inefficient due to GC impact, so it is better to use value receivers.
The criteria for what constitutes a "large" structure is described in the Go Code Review Comments as follows:
If you assume that all values of a structure are passed as arguments: if you feel that is too many, then the structure is large enough to be a pointer.
It is a difficult criterion, but you should decide based on convenience, ease of modification, and GC load.
There is also a note stating, "If you are unsure, use a pointer receiver," so using a pointer when in doubt seems like a good approach.
When storing large structures in a slice
When appending to a slice beyond its cap, or when retrieving elements from a slice using for ~ range, copies of all records are made. Therefore, if you are storing large structures in slice elements, using pointers can reduce the cost of copying.
// If the list lacks capacity, it will be reallocated
list = append(list, x)
// x will be a copy of the list element
for _, x := range list {
...
}
Conclusion
My criteria for choosing between values and pointers have become a bit clearer. Looking at it this way, I think the situations where pointers are truly useful are quite limited.
I couldn't go very deep into the GC load in this article, but @imoty's article was very easy to understand regarding that topic.
Cases where Go's GC overhead becomes high, and their workarounds
Let's use pointers effectively to write maintainable code that is easy for readers to understand.
Discussion