Operator performance

Locked
bitWISE
Posts: 10704
Joined: Wed Dec 08, 1999 8:00 am

Operator performance

Post by bitWISE »

I haven't had any luck searching for the answer and I'm too lazy to code up my own test (maybe I will if no one knows). It is probably language dependent....but is there any performance difference between the two following code samples:

Code: Select all

uint length = someArray.length - 1;
uint n = 0;
while (n != length) {n++;}

Code: Select all

uint length = someArray.length;
uint n = 0;
while (n < length) {n++;}
To a human brain, less/greater than would seem to require an extra step compared to not equal. But when it comes to data in a computer it seems like you would have to compare every bit in until one didn't match in both scenarios. My guess is that not equal is still faster because you can immediately calculate half of all possible comparisons based on the first bit alone.
AnthonyJ
Posts: 130
Joined: Wed Nov 15, 2006 7:51 pm

Re: Operator performance

Post by AnthonyJ »

It's not just language dependent, it is compiler and CPU dependent (and if you're in a language with operator overloading, dependent on whether you or the framework has implemented overriden < and != operators for that type).

On an x86 cpu, probably both will probably be translated into a "cmp" instruction followed by either "jne" (jump not equal), or "jb" (jump if below). Both of them should perform similarly, since the cmp instruction is the same, and both jne/jb are simply testing flags that are set by cmp.

However to be sure you'd need to check the cpu instruction timing charts for your CPU, and confirm that the compiler is generating the "obvious" assembler for your code.
Locked