Return value optimization and GO

977 views
Skip to first unread message

Travis Keep

unread,
May 30, 2013, 3:42:43 PM5/30/13
to golan...@googlegroups.com
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.

Ian Lance Taylor

unread,
May 30, 2013, 3:58:24 PM5/30/13
to Travis Keep, golan...@googlegroups.com
The gc compiler will always return large structs on the stack. It
will not allocate them on the heap.

The extra allocation you are seeing may be due to allocating an
additional stack segment in order to have enough room to return the
large struct on the stack.

Ian
Reply all
Reply to author
Forward
0 new messages