title: MIPS bne beq Computer Organization and Design
body: <p>So, I'll quote my textbook(Computer Organization and Design) and then I'll ask my question:</p>
  <blockquote>
  <h5>Compiling if-then-else into Conditional branches</h5>
  <p>In the following code segment, <code>f, g, j, i</code> and <code>j</code> are variables. If the five variables <code>f</code> through <code>j</code> correspond to the five registers <code>$s0</code> through <code>$s4</code>, what is the compiled MIPS code for this C if statement?</p>
  <pre><code>if (i == j) f = g + h; else f = g - h;
  </code></pre>
  <p>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). <strong>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):</strong></p>
  <pre><code>bne $s3, $s4, Else # go to Else if i ≠ j
  </code></pre>
  </blockquote>
  <p>I've searched for a while but I couldn't find why <code>bne</code> would be more efficient than <code>beq</code>.<br />
  (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.)</p>
  <p>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 branch instruction costs more time if taken, and therefore we'd want to minimize the amount of jumps (taken branches) needed. This means that, when we expect the condition to hold, we should use <code>bne</code>, and when we expect the condition to fail, we should use <code>beq</code>.</p>
  <p>Now if we test whether <code>$s3</code> equals <code>$s4</code>, 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 favour using <code>beq</code> instead of <code>bne</code>.</p>
  <p>So, to sum up: textbook says <code>bne</code> is more efficient than <code>beq</code>, whether it's in general or just in this example is not clear, but in either case I don't understand why.</p>