Is switching variable values with xor faster then the usual way using temporary variable?
XOR variable value switch
Started by MiyamotoSamurai, Aug 27 2009 03:22 AM
4 replies to this topic
#1
Posted 27 August 2009 - 03:22 AM
|
|
|
#2
Posted 27 August 2009 - 06:34 AM
No. On modern CPUs it can be considerably slower, despite what people think. Just because it looks uglier doesn't mean it's faster :P One reason is that modern CPUs want to execute commands in parallel. Using XOR, the commands must be executed in strictly sequential order because the output of the last operation is required as input for the next. It's also error prone (will fail with certain objects, can't swap with yourself etc. etc.) and hard to read. Most modern compilers will optimize swaps if safe and desired. If performance is critical, you should test using both the "normal" temporary variable method and the XOR method to see which is fastest on the target architecture in your case.
Hey! Check out my new Toyota keyboaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#3
Posted 27 August 2009 - 05:59 PM
Now that I know better, I generally prefer
over
XCHG ECX,EDX
over
XOR ECX,EDX XOR EDX,ECX XOR ECX,EDX
sudo rm -rf /
#4
Posted 27 August 2009 - 06:29 PM
XCHG is some kind of a swap command?
By the way we are talking high level programming here not assembly. You can do bitwise stuff with xor from c++ for example.
Anyways just curiuos, is this command faster in assembler then the xor version?
regards
By the way we are talking high level programming here not assembly. You can do bitwise stuff with xor from c++ for example.
Anyways just curiuos, is this command faster in assembler then the xor version?
regards
#5
Posted 27 August 2009 - 06:31 PM
Well, smart compilers would implement it like this, so no, not really. They'd recognize you're trying to swap a variable and just do what I did in my first example.
sudo rm -rf /


Sign In
Create Account


Back to top









