Overhead of Go’s Generic Sort
github.com
github.com
Of course, it becomes less reliable, because you'd have to trust that the compiler does this (and consistently over changes to the code).
It's basically the same as what a JIT compiler does around type inference. If it can reason about the underlying type that's really going to Sort(), it can code generate a specialized version. The machinery for escape analysis that Go already has probably gets you at least part of the way there.
That pretty much boils down to a non-user-controllable templating done entirely through the compiler. Like I said... possible vs desirable.
I just grepped over an in-the-wild Perl source code base. It had 137000 lines of code, of which about 150 had sort in it, of which about half of them were either tests that wanted to maintain key stability[1] or other things that don't generally come up in Go. And this is a language where "sort" is just... "sort". So it is very easy to use, and still doesn't come up that often.
I think it's easy to overestimate how important sorting is. Especially after years of horror stories about bubble sorts taking hours. Most people's primary objection to Go's sort will be the need to write three stupid-simple methods rather than its speed, and in practice that's still just an annoyance rather than a stopper, unless you have a really sort-heavy use case.
[1]: For example, "code that emits HTML attributes specified in a hash". In real code you don't care to sort those, but if you want to verify in modern Perl that {a => 1, b => ">"} gets converted to 'a="1" b=">"', you have to sort because half the time they'll be reversed.
This removes the dynamic overhead at the cost of having to run a code generator and maintain a rendered template library in your source. There's actually language support for hooking into these generators at build time.
Hmm, are you talking about "go generate" or is there a new feature? Because go generate is not a build time hook, but build time hook would be very useful in some cases.
This is just a minor complaint. There is at least a workaround, even if the answer is still typing a bit more than if you used Templates/Generics.
The real take away should be that generics do offer a sizable speed up for the trade off of added complexity. Modern compilers can leverage them to generate very performant code.
[10K elements] BenchmarkLibPotato-4 10000 2166569 ns/op
BenchmarkSpecPotato-4 10000 1020842 ns/op
[10M elements] BenchmarkLibPotato-4 3 3829722562 ns/op
BenchmarkSpecPotato-4 10 1802874882 ns/op