C/C++: is it faster to assign a 0 to an unsigned long variable or to xor the variable with itself?
c, c++, performance, variable-assignment, xor
Solution
If you were to implement a compiler, what would you do? Indeed, you would pick the fastest implementation for both. Since both are equal, this fastest implementation is the same for both.
In other words, any compiler released after 5000 B.C. will generate the same assembly code for both `x = 0` and `x ^= x` if you enable optimizations. This means that they are equally fast.
This doesn't go for only assignment/xorring, but also for multiplication, among other algorithms. Express your intent and let the compiler optimize it. The compiler is better at optimizations than you are, trust me.
In other words, write readable code and use `x = 0;`.
Oh and by the way, bitwise xorring an uninitialized integer by itself is undefined behavior and a good compiler should optimize out the entire thing.
Problem
I realize the difference may be negligible, but which is more efficient in trying to zero an unsigned long? ``` unsigned long x; ... x=0; --OR-- x^=x; ``` Taylor