5 ms·
His logic is wrong. It's not because they are objects, it's because std::sort and friends are function templates. They know what they are calling at compile tim
by sebastic 11y ago
His logic is wrong. It's not because they are objects, it's because std::sort and friends are function templates. They know what they are calling at compile time. Templates allow for compile-time polymorphism like this.
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.
- exDM69 11y ago> C doesn't have templates, therefore it doesn't have compile-time polymorphism, therefore it's much harder for the compiler to inline. 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.