In C++ when returning a large struct or class by value, many modern compilers will optimize away the copy constructor step, assignment step or sometimes both.
Does the go compiler perform similar return value optimization?
I tried code like this in benchmarking.
func NewBigStruct() BigStruct {
return BigStruct{}
}
func Foo() {
bigStruct := NewBigStruct()
ptr := &bigStruct
...
}
If BigStruct is more than about 2K, Foo() results in 2 allocs instead of 1. I assume that NewBigStruct() allocates the BigStruct its returning on the heap and then the bigStruct variable in Foo() is also allocated on the heap. Also the Bytes processed is about 3.5 the actual size of BigStruct suggesting there is no return value optimization. If BigStruct is < 2K, then Foo() does just one alloc and bytes processed is comparable to the size of BigStruct suggesting that there may be return value optimization going on.