reflect typeof without allocating an instance

91 views
Skip to first unread message

ego...@gmail.com

unread,
Mar 25, 2015, 7:20:17 PM3/25/15
to golan...@googlegroups.com
Hi 

TL;DR; version:  `reflect.TypeOf(MyType{})` vs `reflect.TypeOf((*MyType)(nil)).Elem()`


I am exploring the `reflect` package, and was wondering what is the right way to get a hold of a reflect.Type for a given struct.

I saw some samples doing reflect.TypeOf(MyType{}) but wouldn't that cause an allocation of a MyType instance in memory or would the compiler be smart enough to not even cause the allocation (since there are no actual references to it)?

the alternative is to do reflect.TypeOf((*MyType)(nil)).Elem()  


Also, reflect.TypeOf considered heavyweight and results should be cached for recurring usage? if so, the single extra allocation is not a biggie and the intent is clearer over the *nil syntax IMO

So, I lean towards the former but just want to be sure I'm not making some big mistake. Would love to get your opinion.

thanks,
Ken

Ian Lance Taylor

unread,
Mar 25, 2015, 8:18:27 PM3/25/15
to ego...@gmail.com, golang-nuts
On Wed, Mar 25, 2015 at 4:20 PM, <ego...@gmail.com> wrote:
>
> TL;DR; version: `reflect.TypeOf(MyType{})` vs
> `reflect.TypeOf((*MyType)(nil)).Elem()`
>
> I am exploring the `reflect` package, and was wondering what is the right
> way to get a hold of a reflect.Type for a given struct.
>
> I saw some samples doing reflect.TypeOf(MyType{}) but wouldn't that cause an
> allocation of a MyType instance in memory or would the compiler be smart
> enough to not even cause the allocation (since there are no actual
> references to it)?

In principle it reflect.TypeOf(MyType{}) should not require any heap
allocation, since the value does not escape. However, I don't know
offhand if the current compiler is smart enough to see that.


> the alternative is to do reflect.TypeOf((*MyType)(nil)).Elem()

Yes, that works.


> Also, reflect.TypeOf considered heavyweight and results should be cached for
> recurring usage? if so, the single extra allocation is not a biggie and the
> intent is clearer over the *nil syntax IMO

reflect.TypeOf is fast. It's just a few instructions.

Ian

minux

unread,
Mar 25, 2015, 10:17:33 PM3/25/15
to ego...@gmail.com, golang-nuts
On Wed, Mar 25, 2015 at 7:20 PM, <ego...@gmail.com> wrote:
I am exploring the `reflect` package, and was wondering what is the right way to get a hold of a reflect.Type for a given struct.

I saw some samples doing reflect.TypeOf(MyType{}) but wouldn't that cause an allocation of a MyType instance in memory or would the compiler be smart enough to not even cause the allocation (since there are no actual references to it)?
The Go 1.5 compiler is smart enough to only allocate the object on stack, but actually even that's
unnecessary.

Ken Egozi

unread,
Mar 26, 2015, 2:35:31 AM3/26/15
to minux, golang-nuts
Reply all
Reply to author
Forward
0 new messages