by CJefferson · 4y ago · 0 comments
The C++ standard requires that std::sort work for "move-only types", so you can't copy the pivot. I suspect this is where quite a bit of the slowdown happens -- as the pivot has to be taken by reference/pointer, the compiler optimises worse.
Could std::sort implementations optimise for when the pivot can be copied? Certainly! Particularly when it is a "small value" like this. I worked on this years ago for libstdc++ (g++'s std::sort), but it turned out to make the code really horrible, so it was never merged in.
std::sort implementations already use an alternative sort (usually insertion sort) for small sized lists.
Do you mean internally/due to subtle complexity requirements? Cause std::sort works just fine on copyable types like integers and complexity is only defined in terms of swaps.
You could in principle write two implementations, one that moves + swaps, and one that moves, swaps and (occasionally if it really wants to) copies, but it's extremely hard (possibly impossible) to decide when it is "safe" to use the std::sort that can copy.
It turns out it is much easier to optimise if you can copy the pivot into a local variable, but that's hard to do in std::sort.
Here is an implementation. This should work with all types. Unfortunate I had to annotate with restrict, but a small price to pay.