Jump to content

XOR variable value switch

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
MiyamotoSamurai

MiyamotoSamurai

    Learning Programmer

  • Members
  • PipPipPip
  • 35 posts
Is switching variable values with xor faster then the usual way using temporary variable?

#2
marwex89

marwex89

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 10,720 posts
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
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,720 posts
Now that I know better, I generally prefer

XCHG    ECX,EDX

over

XOR    ECX,EDX
XOR    EDX,ECX
XOR    ECX,EDX

sudo rm -rf /

#4
MiyamotoSamurai

MiyamotoSamurai

    Learning Programmer

  • Members
  • PipPipPip
  • 35 posts
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

#5
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,720 posts
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 /