4 ms·
Why is that? There are cases where c++ is faster than C, a typical example is qsort vs std::sort.
by zarkov99 6y ago
Why is that? There are cases where c++ is faster than C, a typical example is qsort vs std::sort.
- skohan 6y agoHow does c++ manage to win here? I'm not doubting, just curious
- _jordan 6y agoThe constexpr specifier should give C++ an advantage
- mhh__ 6y agoProbably not, the compiler doesn't need permission to constant fold of its own accord if it doesn't launch any missiles.
- steveklabnik 6y agoThe classic example is quicksort. qsort takes a function pointer, but std::sort is a template. This means that the machinery can be inlined more often in C++ than C. https://stackoverflow.com/questions/18002087/qsort-vs-stdsort-comparison-function-philosophical-difference https://stackoverflow.com/questions/18002087/qsort-vs-stdsor...
- zarkov99 6y agoIn he case of std::sort the C++ compiler can inline the comparison function when it generates the actual sort implementation from the std::sort template. In C the qsort implementation is fixed and must call the comparison via an indirect reference.
- rurban 6y agoDon't use a libc qsort then. The compiler could generated it (but they don't even generate optimized memcmp yet). Or the CTL is a header only STL for C, which inlines the sort function and the comparator. And because of the C++ bloat and indirect calls the C version is faster. Inlining with macros == constexpr with templates. You can decide which syntax you prefer.
- gpderetta 6y agoTechnically libc couldhave an inline version of qsort in the header or the linker (even the dynamic linker) could do LTO, but bechmarks are done on actual implementations not the mythical sufficiently good compiler.
- tlb 6y agoC++ can inline the comparison function (which is often just a few instructions) at compile time. It can also statically optimize for the stride, using shifts or addressing modes instead of multiplies. C can't do either with qsort, which takes the stride and comparison function pointer as arguments.
- makapuf 6y agoUnless comparison function is small and can be inlined, which would trigger the same stride shift optimizations.