logoalt Hacker News

bbkane • today at 3:32 AM • 1 reply • view on HN

Go doesn't monomorphize, so benchmark your generics- they might not be zero cost


Replies

Groxx • today at 4:22 AM

Go monomorphizes quite a lot, so that's mostly incorrect - it'd be relatively true for Java, for comparison, ignoring Graal. https://github.com/golang/proposal/blob/master/design/generi... there are only exceptions when you instantiate multiple different types that share an underlying type/layout, all other cases (including different types) are monomorphized. E.g. `type x struct{a int, b float32}` and `type y struct{b int, a float32}` share codegen, but if you even just swap the type order (float32 then int) they wouldn't.

The primitive generic atomics in the stdlib don't run into those details, so you really do get pretty much exactly the compiled code as what you'd write inline by hand:

>In particular, fundamentally different built-in types such as int and float64 are never in the same gcshape. Even int16 and int32 have distinct operations (notably left and right shift), so we don’t put them in the same gcshape.