Generics can make your Go code slower
planetscale.com
Generics can make your Go code slower
1–10 of 418 posts
Re: Generics can make your Go code slower
#2Re: Generics can make your Go code slower
#3Re: Generics can make your Go code slower
#4This is a really long and informative article, but I would propose a change to the title here, since "Generics can make your Go code slower" seems like the expected outcome, where the conclusion of the article leans more towards "Generics don't always make your code slower", as well as enumerating some good ways to use generics, as well as some anti-patterns.
Re: Generics can make your Go code slower
#5Re: Generics can make your Go code slower
#6Reading the title I'm worried, should I keep using reflection instead?
Re: Generics can make your Go code slower
#7Good. I saw a lot of people suggesting in late 2021 that you could use generics as some kind of `#pragma force-devirtualization`, and that would be awful if it became common.
Re: Generics can make your Go code slower
#8Reading the title I'm worried, should I keep using reflection instead?
If you're using real interfaces, you should keep using interfaces.
If you care about performance, you should not try to write Java-Streams / FP-like code in a language with no JIT and a non-generational non-compacting GC.
Re: Generics can make your Go code slower
#9Reading the title I'm worried, should I keep using reflection instead?
Just implement naively, then if you have performance issues identify the bottleneck.
Re: Generics can make your Go code slower
#10> Ah well. Overall, this may have been a bit of a disappointment to those who expected to use Generics as a powerful option to optimize Go code, as it is done in other systems languages. We have learned (I hope!) a lot of interesting details about the way the Go compiler deals with Generics. Unfortunately, we have also learned that the implementation shipped in 1.18, more often than not, makes Generic code slower than whatever it was replacing. But as we’ve seen in several examples, it needn’t be this way. Regardless of whether we consider Go as a “systems-oriented” language, it feels like runtime dictionaries was not the right technical implementation choice for a compiled language at all. Despite the low complexity of the Go compiler, it’s clear and measurable that its generated code has been steadily getting better on every release since 1.0, with very few regressions, up until now.
And remember:
> DO NOT despair and/or weep profusely, as there is no technical limitation in the language design for Go Generics that prevents an (eventual) implementation that uses monomorphization more aggressively to inline or de-virtualize method calls.