0
Swap two numbers without a third variable; is it efficient?
Have you seen this short, brilliant code? https://code.sololearn.com/cN6UGN19SXpU/#cs I think it's smart. but how about its performance? Wonder the difference between this code and traditional code with third variable, when translated in assembly codes.
3 Réponses
+ 1
You can use XOR instead. It's slightly faster since it is a bitwise calculation.
a ^= b;
b ^= a;
a ^= b;
+ 1
I think it's good to know, neat trick.
As far as performance, I doubt this is measurable.
For using 3 variables, the compiler is going to optimize the temp variable away. Likely not any different.
Also keep in mind this trick is only going to be of use for whole numbers. Don't do it for decimals.
I think you should stick to temp variables. It's more readable. (The trick is however, still good to know)