In what order in terms of speed (possibly some at equal speed) will the following comparisons run (in if statements):
a) x>k
b) x<k (if k is huge, will this be slower?)
c) x==k
d) x!=k
e) x==k || x==k+1
The difference might be unnoticeable, but can you answer this theoretically? Thanks.
It depends on how the compiler optimizes the code into machine code. Even without optimizations it can differ from one architecture to another. It all depends on what the underlying machine code is capable of doing and how fast the particular processor can do it.
@Duoas: don't forget the world of embedded devices. I have actually worked with a device (a robot microcontroller for high school robotics classes) that only implemented the basic minimal instructions to be usable. Less-than was a single native operation, but greater-than has to be simulated with multiple instructions. (The compiler for this device also had a 24-bit shortlong integer type, which, from what I have heard, is not uncommon in the world of microdevices.)
You make the assumption that this compiler was smart - flipping the operands is something you have to do yourself. (It's really stupid, I know, but trust me - I timed it and it was a real thing)
Though, it has been years since I worked with it - I could be completely misremembering what I am talking about. All I know is that I facepalmed at the stupidity of this microcontroller.
in some uC the instruction are on the way W op F and you may chose to store the result in W or in F.
W is the special `working' register and F may be any register on memory
so to invert the operands you'll need to
1 2 3 4 5
movf aux //dump W
movwf F,w //load register F into the working register
lesswf aux //do the comparison
goto true_case
goto false_case
I guess I meant to say that it may not even be possible to write the code in a way which makes the operands end up in the correct places.
Disclaimer: I don't remember the specifics of the processor, I've only worked with assembly once, I've never worked with machine code. I'm making statements based purely on my intuition.
Well, if the operands are put in that order by a subroutine that's used in several places, I suppose it's better to bite the bullet and flip them than to have two copies of the same subroutine just for that. Otherwise, I fail to see any reason why you couldn't reorder operations to get things in the right places.
// a+b < c
movwf A, w
addwf B, w //w = a+b
lesswf C
gototruegotofalse
// a+b > c -> c < a+b
movwf B, w
addwf A, f //a = a+b, destructive but we are only interested in the result
movwf C, w
lesswf A
gototruegotofalse
greater-than takes me 1 extra instruction than less-than