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
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
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.
First of all, if the variable has not been assigned a value, it is technically "undefined behaviour" to do anything other than assign a value to it.
Second, to XOR it with itself is unlikely to be faster on a processor produced in the last 15-20 years, since it requires an extra read. It may have been faster (due to being SHORTER CODE) a very long time back, but actually, I believe even that is false.
Edit: I should point out that it MAY still be faster/more compact to XOR a register to make it zero in modern processors. But if we assume that we can't know if x
is in a register or not, then we should also not make it more complicated for the compiler to determine what we're actually doing.
Why speculate about what the compiler does? Let's try it out instead!
Here's some test code:
void fzero()
{
unsigned long x;
x = 0;
}
void fxor()
{
unsigned long x;
x ^= x;
}
int main()
{
fzero();
fxor();
}
And now lets look at the resulting machine code:
; 10 : unsigned long x;
; 11 :
; 12 : x ^= x;
; 13 : }
00000 c2 00 00 ret 0
; 3 : unsigned long x;
; 4 :
; 5 : x = 0;
; 6 : }
00000 c2 00 00 ret 0
PUBLIC main
; Function compile flags: /Ogtpy
; COMDAT main
_TEXT SEGMENT
main PROC ; COMDAT
; 18 : fzero();
; 19 : fxor();
; 20 : }
00000 33 c0 xor eax, eax
00002 c3 ret 0
main ENDP
Oh, Look! They were equally fast, both taking exactly 0 ns.