So, I'll quote my textbook(Computer Organization and Design) and then I'll ask my question:
Compiling if-then-else into Conditional branches
In the following code segment, f, g, j, i and j are variables. If the five variables f through j correspond to the five registers $s0 through $s4, what is the compiled MIPS code for this C if statement?
if (i == j) f = g + h; else f = g - h;
Figure 2.9 is a flowchart of what the MIPS code should do. The first expression compares for equality, so it would seem that we would want the branch if registers are equal instruction (beq). In general, the code will be more efficient if we test for the opposite condition to branch over the code that performs the subsequent then part of the if (the label Else is defined below) and so we use the branch if registers are not equal instruction (bne):
bne $s3, $s4, Else # go to Else if i ≠ j
I've searched for a while but I couldn't find why bne would be more efficient than beq. (I did however find that bne is sometimes recommended because it makes the code easier to understand, as the statements to be executed when the condition holds are right below the bne statement.)
So, if it would not be more efficient in general, it still could be more efficient in this particular exercise. I've thought about that, and I assumed that a jump instruction costs time, and therefore we'd want to minimize the amount of jumps needed. This means that, when we expect the condition to hold, we should use bne, and when we expect the condition to fail, we should use beq.
Now if we test whether $s3 equals $s4, when we have no information whatsoever about the content of those registers, it's not reasonable to assume that they're likely to be equal; on the contrary, it's more likely that they're not equal, which should result in using beq instead of bne.
So, to sum up: textbook says bne is more efficient than beq, whether it's in general or just in this example is not clear, but in either case I don't understand why.
bneis seen to be "more efficient" is a psychological one where coders tend to write code of the formif (most_likely_condition) something(); else something_else();. That, along with branchless code being more cache-friendly, might tend to make "the opposite condition" "more efficient". - twalbergbneandbeq. <br> <br> Consider that two instructions are comparing two register. The operation ofbeqmust go through every bit to give an answer and store it to the register of destination. On the other hand,bnemight counter difference in first few. <br> <br> I don't have any solid evidence for the hypothesis. I'm really glad if someone can back this up or op - Vibert Thio