且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与零比较是否比与任何其他数字比较快?

更新时间:2023-11-29 09:29:16

通常,是的.在典型的处理器中,针对零进行测试或测试符号(负/正)是简单的条件代码检查.这意味着可以重新排序指令以省略测试指令.在伪汇编中,考虑一下:

Typically, yes. In typical processors testing against zero, or testing sign (negative/positive) are simple condition code checks. This means that instructions can be re-ordered to omit a test instruction. In pseudo assembly, consider this:

Loop:
  LOADCC r1, test // load test into register 1, and set condition codes
  BCZS   Loop     // If zero was set, go to Loop

现在考虑针对 1 进行测试:

Now consider testing against 1:

Loop:
  LOAD   r1, test // load test into register 1
  SUBT   r1, 1    // Subtract Test instruction, with destination suppressed
  BCNE   Loop     // If not equal to 1, go to Loop

现在是通常的优化前免责声明:您的程序是否太慢?不要优化,分析它.

Now for the usual pre-optimization disclaimer: Is your program too slow? Don't optimize, profile it.