4 ms·
Monomorphization is one of the ways generics are implemented in other languages and it definitely allows for type-specific optimizations. I imagine there's a r
by Gadiguibou 4y ago
Monomorphization is one of the ways generics are implemented in other languages and it definitely allows for type-specific optimizations.
I imagine there's a rationale for not implementing generics this way, like keeping binaries small, but it seems like a weird tradeoff considering it increases overall memory consumption and decreases performance quite a lot...
- cube2222 4y agoIf I understood the implementation correctly, as long as you use value types instead of pointer/interface types for your generic type parameters, you'll basically get monomorphization.
- throwaway894345 4y agoI don’t think this is true. If your value types use methods in the generic code, I think you get dictionaries regardless (maybe Go doesn’t emit dictionaries if there is exactly one implementation for a gcshape?). Value types just make it more likely that you’ll have distinct gcshapes, but I’m pretty sure you’ll still get dictionaries. The only way you don’t is if you have a pure container (no calling methods on type parameters). That said, I believe there’s an undocumented flag to force full monomorphization, but it’s probably not stable.
- fsdjkflsjfsoij 4y agoIf it was up to me I would have gone with full monomorphization because I don't care about binary size or compilation time quite as much as the current Go developers. However, the decrease in performance of the current implementation is being vastly overstated because people read a single article. It's not going to be even close to a bottleneck in all but the most extreme performance demanding applications and those applications probably shouldn't be using a garbage collected language to begin with.
- mseepgood 4y agoThere are two possible extremes for the implementation of generics: full monomorphization on one side, and dictionaries on the other side. Both have serious drawbacks: monomorphization is faster, but produces bloat, and dictionaries are slower but don't produce bloat. Go chose to combine the two for a middle ground. It's a bit more complicated to implement than just monomorphization or just dictionaries, but it provides a nice balance.
- fsdjkflsjfsoij 4y agoI agree with everything you wrote but would add that it's even more complicated because there are cases, albeit rare in my experience, where full monomorphization produces slower code due to cache misses. I believe std::format in C++ is generally considered an example of this https://youtu.be/zssTF1uhxtM?t=2021 https://youtu.be/zssTF1uhxtM?t=2021
- throwaway894345 4y agoI think it’s about keeping binaries small and compile times fast. I suspect they’ll monomorphize more in the future, but they want to proceed incrementally, which seems reasonable to me.