Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is It More Efficient to Do a Less Than comparison OR a Less Than Or Equal To?

I'm wondering if it's more efficient to do a less than or equal to comparison in a loop or a less than comparison. Does the <= operator instruct the computer to make two comparisons (is it less than, is it equal to), or does it simplify it? Take the following example. I want a loop than increments to 1000. Should I set the ceiling to 1001 and tell it that while i is < (OR !=) 1001, i++;? Or should I tell it that while i <= 1000, i++;? Will the compiler (GCC) simplify it to the same basic instructions?

like image 714
wafflesausage Avatar asked Mar 14 '14 03:03

wafflesausage


People also ask

Which operator is used for less than or equal to?

The less than or equal operator ( <= ) returns true if the left operand is less than or equal to the right operand, and false otherwise.

Is the number less than or equal to zero Javascript?

To check if a number is not greater than 0 , check if the number is less than or equal to 0 , e.g. num <= 0 . If the condition returns true , the number is not greater than 0 .

How to check less than in javascript?

The less than operator ( < ) returns true if the left operand is less than the right operand, and false otherwise.


2 Answers

The machine level architecture will have OP codes for both < and <= operations and both comparisons can be made in one cycle of the CPU. Meaning it makes no difference.

like image 196
Paperwaste Avatar answered Nov 15 '22 07:11

Paperwaste


It depends on the architecture.

The original von Neumann IAS architecture (1945) did have only >= comparison.

Intel 8086 can use Loop label paradigm, which corresponds to do { } while (--cx > 0);
In legacy architectures, LOOP was not only smaller, but faster. In modern architectures LOOP is considered complex operation, which is slower than dec ecx; jnz label; When optimizing for size (-Os) this can still have significance.

Further considerations are that some (RISC) architectures do not have explicit flag registers. Then comparison can't be given free, as a side effect of loop decrement. Some RISC architectures have also a special 'zero' register, which means, that comparison (and every other mathematical operations) with zero is always available. RISCs with jump delay slots may even benefit from using post decrement: do { } while (a-- > 0);

An optimizing compiler should be able to convert a simple loop regardless of the syntax to the most optimized version for the given architecture. A complex loop would have a dependency to the iterator, side effects, or both: for (i=0;i<5;i++) func(i);.

like image 43
Aki Suihkonen Avatar answered Nov 15 '22 05:11

Aki Suihkonen