> In Go, I found that using an interface was not free: it can make the code slower.
The Go version that was presented isn't equivalent though. In Go you are accepting an interface directly which will hide the value under some fat pointer for dynamic dispatch, in c++ you are using generics to monomorphise the function to specific types. If you want to compare the implementations fairly you should've used Go generics:
Fair criticism, though I do wonder if it'd really make that much of a difference. Go doesn't really monomorphize generics either, and would end up with an equally if not more expensive lookup for the correct generic function at runtime.
That's true at the moment, but still an implementation detail. I think I remember early versions of C++ compilers doing the same thing with templates.
Considering the progress Go compiler has gone through, I think it's reasonable to expect the optimized implementations will come few versions down the road.
Not the OP, however I have programmed in C++ since 1987 across many different operating systems and hardware platforms and I've literally never heard of a compiler that implements template stuff using runtime dispatch. CFront3 which was I think the first real template implementation that most people used certainly never did it that way, neither did any version of gcc, visual studio or Sun Workshop, which are the compliers I used the most from that period. Dug out my old copy of Coplien[1] which is from the early 90s and it discusses runtime dispatch in depth in the context of vtables and virtual function pointers and the cost of these things, so the concept was well understood but not a cost anyone was paying with templates.
[1] https://archive.org/details/advancedcbsprogr00copl "Advanced C++ Programming Styles and Idioms" aka the first programming book that genuinely kicked my ass when I first read it and made me realise how good it was possible to be at computer science.
Right. For starters, from the very beginning C++ has supported function templates which take native types. So you don't even necessarily have any kind of pointer you could add a vtable to even if you wanted to. Then add to that the guarantee[1] about pod types being directly compatible with C which as you say I don't see how it owuld be possible to do.
[1] which has always been strong even before there was an actual ISO/ANSI standard
templates don’t exist after the front end. there is no ABI that allows them to exist in any object file. there is no object file format they could be embedded in, sans a string representation of the source they came from.
The Go version that was presented isn't equivalent though. In Go you are accepting an interface directly which will hide the value under some fat pointer for dynamic dispatch, in c++ you are using generics to monomorphise the function to specific types. If you want to compare the implementations fairly you should've used Go generics: