which one is theoretically faster on x86 CPUs:

if (a && b)? ?{? ?code? ?}

which generates 2 jumps, like:
cmp a, 0
jz
cmp b, 0
jz


or

if ( (a & b)? ||? (a | b) )? ? {? ?code? ?}


mov eax, a
and eax, b
test eax, eax
jz
mov eax, a
or eax, b
test eax, eax
jz


which also generates 2 jumps, but the first one succeeds (actually jumps) 100% of the time, while the second one is only an emergency , and in practicice never happens (assuming -for example- that both 'a' and 'b' are valid pointers) .

?

The second option should be better due to branch prediction, shouldn' it? (let's say i execute this 'IF' statement 500 times/second)

/edit

or maybe
if ( (a & b)? ^? (a | b) )? ? {? ?code? ?}


mov eax, a
and eax, b
mov ecx, a
or ecx, b
xor eax, ecx
test eax, eax
jz


This generates only 1 jump, but I haven't tested it in all of the cases yet. (I'm too sleepy now :P )

Posted on 2005-08-11 00:49:12 by ti_mo_n
Your logic is wrong in the second case, it should be:

if ((a & b) && (a | b)) { code }

This is what you've coded the assembly as though.

Also the test lines aren't needed as the and instruction, and the or instruction both set the zero flag.

Mirno
Posted on 2005-08-11 04:52:36 by Mirno
The if (a && b) should require only a single jump with:


mov eax,a
or  eax,b
jz          ; the Z flag would be set if and only if both a and b are 0


The AND and XOR instructions are useless for testing values of 0. For example,

1 & 2 = 0
3 ^ 3 = 0

Raymond
Posted on 2005-08-11 09:15:13 by Raymond
Mirno, yes - you're right with this assembly, but the && and || themselves don't matter rally, since we have De Morgan's law ;) I just wanted to know if it's worth to sacrifice some instructions to get rid of useless jumps.

Raymond,  a && b  is not equal with  mov eax, a ;  or eax, b;

a && b  passes THEN AND ONLY THEN when _BOTH_ a AND b  are NON-ZERO, while:

mov eax, a
or eax, b


generates a non-zero eax even when either a OR b (or both) are non-zero.

----

My question stays the same: is it worth trying to avoid jumps this way?
Posted on 2005-08-11 14:51:23 by ti_mo_n

I just wanted to know if it's worth to sacrifice some instructions to get rid of useless jumps.


The real question is, do you think it is worth it? I personally enjoy doing such optimizations, it makes the code nice and clean.
Posted on 2005-08-11 15:00:55 by SpooK