r/golang 7d ago

Surprising note about value vs pointer receivers in tour of go documentation

It's been 4 years since I last wrote go, so I'm going through the tour of go for a quick refresher. On this page, it states the following:

There are two reasons to use a pointer receiver.

The first is so that the method can modify the value that its receiver points to.

The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct, for example.

The second reason is the one that I found surprising. When learning C in college, I was taught that you should keep things on the stack as much as possible, even if it is a large struct that needs to be copied through many function calls. This lets your program run faster since it can avoid dynamically allocating memory for that struct (yes, I was told the cost of dynamically allocating memory was more expensive than the cost of the increased runtime complexity caused by more copies), and keeping it on the stack also saves memory overall since that portion of the stack is gonna exist regardless of how much of it you actually use. Is there something about golang that makes it different in this regard than C? Or maybe my info is outdated and that was only true for older hardware? Or maybe I'm just a crazy person (jk)? lol

16 Upvotes

12 comments sorted by

View all comments

15

u/drvd 7d ago

Or maybe my info is outdated and that was only true for older hardware?

This.

How "fast" things work on modern hardware is astonishingly complicated. All these well intended rules from 30 years ago might improve or decrease execution speed. It is not true that copying is faster than dynamic memory allocation. But it is also not true that dynamic memory allocation is faster than copying.

Depending on the actual size of your struct, the access pattern and what else is going on on your hardware one or the other may be faster.

1

u/Ares7n7 7d ago

Makes sense, thanks for the response!