Interface() method of reflect.Value sometimes allocates, sometimes not

90 views
Skip to first unread message

christoph...@gmail.com

unread,
Jun 26, 2023, 3:28:31 PM6/26/23
to golang-nuts
I'm implementing a value encoder similar to gob. While bench-marking my code against gob, I noticed some unexpected memory allocations with a particular type of data.

See this minimal code example in the go playground https://go.dev/play/p/4rm-kCtD274

There is a simple function foo() receiving a []uint reflect.Value as input. It calls the Interface() method to get back a []uint value that it can then use.

When the input value is a []uint, the Interface() method doesn't allocate.

When the input value is a []uint of a [][]uint (a matrix), the Interface() method allocates the slice header on the heap.

I was wondering if this is just a limitation of optimization or if there was a constrain imposing the allocation.

In my code and gob's code (see the helpers functions in enc_helpers.go) the slice returned by Interface() is only used locally.


Ian Lance Taylor

unread,
Jun 26, 2023, 5:29:16 PM6/26/23
to christoph...@gmail.com, golang-nuts
The key difference here is not the type, it's that in the latter case
the reflect.Value is addressable. That is, the CanAddr method will
report true. In that case the reflect package returns a new copy of
the value. Otherwise it would be possible for the value in the
returned interface to be changed via the reflect.Value, which is not
how interface types work.

Ian
Reply all
Reply to author
Forward
0 new messages