成本==运算符vs<或者>运营商

时间:2012-06-24 16:40:10

标签: performance operators micro-optimization

这实际上只是一个学术问题,我只是想知道哪一个更快。我猜这种差异可以忽略不计,但我仍然想知道。

if( (x == 1) || (x == 2) )

VS

if (x < 3)

谢谢!

1 个答案:

答案 0 :(得分:5)

在您提供的表单中,复杂性存在明显差异:第一个代码使用3个运算符,然后第二个代码 - 只使用一个运算符。但是好的,我们可以使用此代码并假设您要比较>(或<)和==!=)。如果你在考试你的课程时遇到过汇编程序(但我打赌你没有),你会注意到这样的代码

if (x < 3) /* action */;

被翻译为smth(对于x86 CPU):

  cmp %eax, 3   // <-- compare EAX and 3. It modifies flags register(*1) (namely ZF, CF, SF and so on)
  jge @@skip    // <-- this instruction tells CPU to jump when some conditions related to flags are met(*2).
                // So this code is executed when jump is *not* made (when x is *not*
                // greater or equal than 3.
  /* here is action body */
@@skip:
  // ...

现在考虑以下代码:

if (x == 3) /* action */;

它将提供几乎相同的程序集(当然,它可能与我的不同,但不是语义上的):

  cmp %eax, 3
  jne @@skip // < -- here is the only difference
  /* action is run when x is equal to 3 */
@@skip:
  ...

这两个运算符(jgejne以及其他运算符都以相同的速度完成它们的工作(因为CPU是这样做的,但显然取决于它的架构)。对性能的影响越大,跳跃距离(代码位置之间的差异),缓存未命中(当处理器错误地预测跳转时)等等。有些指令甚至更有效(例如使用更少的字节),但要记住唯一的事情:不要付出那么多的注意力。最好进行algorythmic优化,不要在匹配上节省成本。让编译器为您完成 - 它在这些问题中更有能力。专注于你的算法,代码可读性,程序架构,容错。使速度成为最后一个因素。

(* 1):http://en.wikipedia.org/wiki/FLAGS_register_%28computing%29
(* 2):http://www.unixwiz.net/techtips/x86-jumps.html

相关问题