3 ms·
The better way to deal with having to swap two items is to ensure they end up in the right spot in the first place. Seeing a 'swap' is usually a sign of somethi
by jacquesm 5y ago
The better way to deal with having to swap two items is to ensure they end up in the right spot in the first place. Seeing a 'swap' is usually a sign of something being wrong a bit upstream.
- wheybags 5y agoWhat about inside the implementation of a sorting routine? Or the move assign operator of a smart pointer? There are plenty of legitimate reasons to swap variables, not everyone is making a crud app.
- jacquesm 5y agoWhen implementing a sorting routine the typical 'swap' operation is two loads and stores from memory, and the order of the loads and stores is what effects the swap, you don't typically do swap-in-place with memory.
- xanathar 5y ago99.9% of the time swaps are done for a reason, usually when sorting or manipulating linked lists pointers, but - for example - comes into play also when you want to transpose a matrix in place, or other similar algorithms. I guess you can make an argument that the best way to get an array sorted is to have the array already sorted, but that sounds as "the best way to calculate the length of the hypotenuse is to just measure the hypotenuse, and Pythagoras never realized it was a problem upstream".
- jacquesm 5y agoOf course swaps are done 'for a reason'. But this is an implementation detail for a swap, one where the xor trick is used to be able to swap 'in place' without using a third variable to perform the swap, and that screams 'register constraints'. To get into that situation is the mistake, not to get clever to use an xor swap to get you back out of it. In any other situation that realistically speaking would occur such constraints would not normally exist.
- sokoloff 5y agoIn a sorting algorithm, if the XOR swap (or any other trick) is faster, that seems a valid use case. The constraint being “this sort library should be correct first and as fast as possible second.”
- jacquesm 5y agoI've implemented lots of sorting algorithms and have never found the XOR trick useful or faster. The main use was on very register constrained 8 bit machines but I haven't programmed on anything like that in assembly for years. Still, it's a neat trick.