In the form you provided there is evident difference in complexity: the first code uses 3 operators, then the second — just one. But OK, lets put this code of and assume you want to compare >
(or <
) and ==
(!=
). If you have ever faced assembler while examing your programs (but i bet you didn’t) you would notice such code
if (x < 3) /* action */;
being translated to smth like (for x86 CPU):
cmp %eax, 3 // <-- compare EAX and 3. It modifies flags register(*1) (namely ZF, CF, SF and so on)
jge @@skip // <-- this instruction tells CPU to jump when some conditions related to flags are met(*2).
// So this code is executed when jump is *not* made (when x is *not*
// greater or equal than 3.
/* here is action body */
@@skip:
// ...
Now consider this code:
if (x == 3) /* action */;
It will give almost the same assembly (of course, it may differ from mine, but not semantically):
cmp %eax, 3
jne @@skip // < -- here is the only difference
/* action is run when x is equal to 3 */
@@skip:
...
Both of this operators (jge
and jne
and others jumps) do their job with the same speed (because CPUs are made so, but it obviously depends on its architecture). The more impact on performance does distance of jump (difference between code positions), cache misses (when processor wrongly predicted the jump), and so on. Some instructions are more effective even (use less bytes for example), but remember the only thing: do not pay them so much attention. It always better to make algorythmic optimizations, don’t do savings on matches. Let the compiler do it for you — it is really more competent in such questions. Focus on your algorythms, code readablity, program architecture, fault-tolerance.. Make speed the last factor.
(*1): http://en.wikipedia.org/wiki/FLAGS_register_%28computing%29
(*2): http://www.unixwiz.net/techtips/x86-jumps.html
6
solved cost of == operator vs < or > operators [closed]