0

I've come from C++ world with such things like the move semantic and RVO. Since that, I wonder are there any trade-offs when you pass arguments by value?

In my case, I have pretty big structs that I need to pass to a bunch of functions. As I have understood, every time I pass a value to a function, a copy will be created. Would it be better to pass pointers instead of values?

I see the only trade-offs that the original object could be changed accidentally or ignorantly, and it is unclear for a caller that a passed argument is not supposed to be modified.

Is there an optimization if a passed value has not been modified?

Dení
  • 183
  • 1
  • 9

1 Answers1

4

There's no optimization for this, and everything will get copied around. It comes down to the amount of distinct fields being copied (i.e. if you have a member that is a struct, the number of fields in it matter as well of course).

So if you have very complex structs, and performance is so critical that this might become a bottleneck, then you should use pointers even for immutable stuff.

I've written a little benchmark that calls a method that does nothing on a struct with 15 fields. One method is a pointer and the other is a value method. the result:

BenchmarkValue  100000000           12.1 ns/op
BenchmarkPointer    2000000000           0.42 ns/op
Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
  • Thanks for the answer and code. Interesting, ``% go version go version go1.5.2 darwin/amd64 % go test -bench . -benchmem testing: warning: no tests to run PASS BenchmarkValue-8 200000000 8.53 ns/op 0 B/op 0 allocs/op BenchmarkPointer-8 2000000000 0.30 ns/op 0 B/op 0 allocs/op ok github.com/test/test 3.246s`` Sorry for such formatting. – Dení Jan 10 '16 at 02:45
  • Mine was with go 1.4 – Not_a_Golfer Jan 10 '16 at 05:44