4 ms·
Why do we use xorl to store 0, but mov for 1? mov $1, %eax xorl %ebx, %ebx # Why not mov for this one? mov $0, %ebx # Wouldn't this work as well? I'm
by unoti 15y ago
Why do we use xorl to store 0, but mov for 1?
mov $1, %eax
xorl %ebx, %ebx # Why not mov for this one?
mov $0, %ebx # Wouldn't this work as well?
I'm guessing mov would work in either case, but there's some reason people always do the xorl instead?
- ori_b 15y agoPerformance. For this example it doesn't matter, but if you're trying to optimize something in assembly it tends to be a good habit.
- grimlck 15y agoThe xorl instruction uses fewer bytes than the mov. (The movl instruction encoding has the bytes needed for a 32 bit constant, while the xorl instruction encoding would not)
- bdonlan 15y agoThe xorl is one byte smaller, and can be faster. On modern CPUs it's more about the compactness of code than speed, but on some embedded CPUs you can save a cycle or two this way.
- alexscheelmeyer 15y agoBoth will work. The xor version is an old trick that many years ago was faster to execute. I do not think that is still the case, but there is still the difference that the XOR opcode is only one byte and the mov version is multiple, so it saves a few bytes in the executable.
- jevinskie 15y agoMore importantly, these days, is that it saves a few bytes in the caches.
- deleted 15y ago[deleted]
- maximilianburke 15y agoI think in this case it's a case of not being able to easily determine if "mov ebx, 0" is copying a value into a subregister, making the result dependent on previous operations, or if it's clearing a register. With xor (and sub too, I believe) the processor assumes that no such dependencies exist and can execute the instruction in parallel with others.
- xpaulbettsx 15y agoThe XOR is also more idiomatic assembly (even though it's not intuitive, every compiler does it and people who know assembly are used to it)
- Someone 15y agohttp://stackoverflow.com/questions/1135679/does-using-xor-reg-reg-give-advantage-over-mov-reg-0 http://stackoverflow.com/questions/1135679/does-using-xor-re... gives more answers than you want, especiallly if you read that Intel PDF. It is not 100% a "smaller is better" choice. You also will want to check whether an instruction depends on an earlier one (for example, the XOR technically needs to read the register; if the CPU does not know that that is not actually the case, a self-XOR may introduce pipeline bubbles), what instruction unit (if any) it uses, and whether you want to preserve flags.