好的,我将引用我的教材(计算机组成与设计),然后提出我的问题:
我搜索了一段时间,但我找不到为什么bne比beq更高效的原因。(但是我发现有时会推荐使用bne,因为它使代码更易于理解,当条件成立时要执行的语句就在bne语句下面。)Compiling if-then-else into Conditional branches
In the following code segment,
f, g, j, i
andj
are variables. If the five variablesf
throughj
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
所以,如果在一般情况下它不会更高效,那么在这个特定的练习中它仍然可能更高效。我思考了一下,假设分支指令在被执行时需要更多的时间,因此我们希望尽量减少所需跳转(已执行分支)的数量。这意味着当我们期望条件成立时,我们应该使用bne,而当我们期望条件失败时,我们应该使用beq。
现在,如果我们测试
$ s3
是否等于$ s4
,当我们对这些寄存器的内容没有任何信息时,假设它们可能相等是不合理的。相反,更有可能它们不相等,这应该支持使用beq
而不是bne
。总之:教科书说bne比beq更高效,无论是普遍情况还是只针对这个示例都不清楚,但在任何情况下我都不明白为什么。
bne
被认为“更高效”的原因是心理上的,程序员倾向于编写形式为if (most_likely_condition) something(); else something_else();
的代码。这个以及无分支代码更加缓存友好,可能会使“相反的条件”“更高效”。 - twalberg