https://godbolt.org/z/zTe8jocsE
Now tell me I need generics for this to get optimized. (Generics are useful for type safety, which you can add using macros in C, but this is then ugly).
>Now tell me I need generics for this to get optimized.
Generics are explicit and reliably optimized. Implicit function pointer optimization is non-obvious and optimized unreliably.
To reliable devirtualize function pointers in C you need to use non-standard extensions. But the best strategy is not let the optimizer decide and apply this very carefully inly for the few selected cases where it matters.
Choose to believe this, it's your loss. The fact is that performance sensitive domains like browsers/HFT/HPC/ML/etc are almost universally written in heavily templated C++. Just look at linear algebra libraries, C can't compete.
> They create specialized inline code by monomorphization
Neither generics nor monomorphization imply inlining, that's purely a performance optimization.
> (except partially in Go which is a bit smarter).
Are you joking? Go, already an extremely bloated language, somehow managed to implement generics with runtime overhead.
> Generics always create the bloat by default.
Generics only generate code you would have manually written/copied otherwise.
> But the best strategy is not let the optimizer decide and apply this very carefully inly for the few selected cases where it matters.
Two words, heterogeneous programming.
Yes, you just compiled C code as C++. Actually write it as C++ (get rid of the void* mostly) and your program becomes a constant time evaluation: https://godbolt.org/z/5fedo8s5q
I added a little fix which prevents the compiler from discarding the result completely (just by going through __builtin_printf()):
https://godbolt.org/z/W93WrhbaE
PS: another minor tweak (make the comparison function static, so that no extra copy is included in the compiler output):