Re:Rust is now overall faster than C in benchmarks
by skohan on Sunday January 03, 2021 @02:22PM
(#25624304)
How does c++ manage to win here? I'm not doubting, just curious
[ Parent
| on HN ]
Re:Rust is now overall faster than C in benchmarks
by steveklabnik on Sunday January 03, 2021 @02:25PM
(#25624337)
The 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-stdsor...
Re:Rust is now overall faster than C in benchmarks
by tlb on Sunday January 03, 2021 @02:28PM
(#25624361)
C++ 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.
Re:Rust is now overall faster than C in benchmarks
by makapuf on Sunday January 03, 2021 @06:47PM
(#25626422)
Unless comparison function is small and can be inlined, which would trigger the same stride shift optimizations.
Re:Rust is now overall faster than C in benchmarks
by zarkov99 on Sunday January 03, 2021 @02:27PM
(#25624351)
In 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.
Re:Rust is now overall faster than C in benchmarks
by gpderetta on Sunday January 03, 2021 @02:33PM
(#25624408)
Technically 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.
Re:Rust is now overall faster than C in benchmarks
by rurban on Sunday January 03, 2021 @05:45PM
(#25625956)
Don'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.