FIRSTLY, this question is NOT about for
loop performance. That is just the background.
So, I somehow found out that when using Java, counting down the for loops is much faster than counting up the loop. I mean, for(int i=0; i < n; i++)
is way slower than for(int i=n-1; i >=0; i++)
. (Yes, I do know that premature optimization is the root of all evil, but I just wanted to find out the reason). So, this led me to think that the difference is because of how cmp
is implemented in machine-level language. One of the ways I could think of regarding writing compare
function natively is like this:
public int compare(int a, int b) {
int diff = a-b;
if(diff == 0) {
return 0;
}
if(b ==0) {
return((is MSD of a 1)?-1:1);
}
return(diff,0);
}
And I can check the MSD bit by right-shifting the number by bit-machine size and see if it's a 1 or 0. BUT, even for this, I'd be needing ==
. That will again come back to the same problem. So, my question is, at the assembly or machine level, how are <,>,==
implemented just using bitwise operations and maybe jmp
sequences?