That's insight I've never seen anywhere before.
That's insight I've never seen anywhere before.
The "C++ with lambda is faster than C with function" comes from C's qsort function that takes a function pointer to a comparator and is not inlined by the compiler. This can result in it being slower than std::sort.
BTW since lambdas without capture decay to function pointers, you can pass such a lambda to qsort.
This is a matter of compilation units, not C vs. C++. If you put qsort() in a header file, and call it with a function pointer in the same compilation unit, it will get inlined and work exactly the same way as std::sort (which is in a header file since it's a template).
You can pretty easily verify this yourself by doing a C++ template and a C function with function pointers (in a header file!), compile and inspect the resulting assembly code.
Link-time optimization may relax the compilation unit requirement, but it's not very widely used yet.
Because of compile-time polymorphism, you can pass in prvalue function pointers and objects alike and the compiler will be able to inline.
C doesn't have templates, therefore it doesn't have compile-time polymorphism, therefore it's much harder for the compiler to inline.
Compilers like GCC and Clang can inline in some runtime-polymorphism circumstances. See -flto and -fdevirtualize.
A C compiler can do the same inlining and optimizing as long as the called function (e.g. qsort) and the function that's pointed-to (e.g. the comparison function) are in the same compilation unit.
C++ templates do not add any magic here, std::sort() is simply faster because it's in a header file and qsort() is not. If you pass a function pointer to a function in a different object file to std::sort, it won't have a lot of advantages over qsort in terms of optimizations/performance (it still does know sizeof(T), though).
Link-time optimization should make standard qsort-type functions perform similarly to std::sort.
Whoever says C++ is slower than C is misinformed and/or overgeneralizing.
Professional C++ programmers know this already though.
A generic collection is usually faster when implemented using templates instead of void*.
And std::function, from what I understand, is generally not as fast as a function pointer, a stored lambda, a function object, since it must do some run-time checks to see how to call what it is storing.
Whenever you need to make a function virtual in C++, you'd need to store a function pointer in an equivalent C design, somehow.