Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why use or instead of cmp when checking against 0 [duplicate]

Tags:

x86

assembly

Is there a major positive quality when using "or" instead of "cmp"?

Consider this function prologue:

push  ebp
mov   ebp,esp
push  ebx

xor   eax,eax        ;error return code
mov   ecx,[ebp +8]   ;first integer arg after return addr.
mov   edx,[ebp +12]  ;second integer argument

The function shall calculate a / b or a % b.
First I need to check against a 0 divisor.

My intuitive move would be to assemble

cmp  edx,0
je   InvalidDivisor

But when I look into advanced books on assembler there would be used this:

or   edx,edx
jz   InvalidDivisor   

My question is why is this second solution "more correct"?
Would it not take longer to calculate an or-operation and check for zero-flag than just compare two values?

Is it just a matter of more advanced coding style?

like image 382
clockw0rk Avatar asked Dec 19 '22 08:12

clockw0rk


1 Answers

or edx,edx is two bytes, cmp edx, 0 is three so you know which to pick if you care about the size.

If you care more about speed then you actually need to measure. Or will obviously "change" the register and might add latency if the next instruction uses the same register.

The best choice for comparing a register with zero is test reg, reg.

83 fa 00  cmp    edx,0x0
09 d2     or     edx,edx ; Smaller
85 d2     test   edx,edx ; Smaller and better, updates ZF but does not store the result
like image 167
Anders Avatar answered Feb 18 '23 20:02

Anders