10 ms·
It's more to do with the fact that std::sort's definition is visible to the compiler and qsort() is not. Put qsort() code in stdlib.h, make it static and write
by mh7 6y ago
It's more to do with the fact that std::sort's definition is visible to the compiler and qsort() is not.
Put qsort() code in stdlib.h, make it static and write a static intcmp() and you'll see the compiler inline that no problem.
- ryanianian 6y agoSure you can hard-code intcmp into qsort but then it would only work for arrays of ints. You could do some macro magic instead of templates e.g. `DEFINE_QSORT(int, intcmp)` which could stamp out `qsort_int` but that's not a part of the stdlib. C++ arguably gets this right since sort<int> and sort<string> will be separate functions, although templates are of course a footgun. And of course duping the logic for std::sort<T> for a bunch of different T impls increases the binary size.
- marvy 6y agoI think mh7 did not mean to hard-code intcmp into qsort. The idea is to move the definition of qsort directly into the stdlib.h header file. That way, the compiler can see the definition of qsort and intcmp at the same time. In that case, the compiler could make a specialized qsort using intcmp automatically.
- TheNewAndy 6y agoThe poster you are replying to didn't suggest hardcoding intcmp into qsort - just making it so the implmentation of qsort is available to the compiler when the comparison function is known (i.e. just like with C++). When this is done, the compiler can inline qsort, and replace the indirect function call with an inlined version of intcmp, and then things are equivalent.
- bluGill 6y agoOnly if inlining qsort is best. Sometimes it is sometimes it isn't, based on complex rules that I trust the compiler to know.
- deleted 6y ago[deleted]
- deleted 6y ago[deleted]
- jjgreen 6y agoI've done this a few times using http://www.corpit.ru/mjt/qsort.html http://www.corpit.ru/mjt/qsort.html
- steerablesafe 6y agoI'm skeptical. I doubt that the whole of qsort gets inlined (it's big), and the best the compiler can do is to clone qsort to const-propagate the function pointer for it to get inlined. In my similar experiments with std::sort with a function pointer only gcc does this with -O3.