==运算符vs <或>运算符的开销

Vin*_*ent -5 performance operators micro-optimization

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

if( (x == 1) || (x == 2) )
Run Code Online (Sandbox Code Playgroud)

VS

if (x < 3)
Run Code Online (Sandbox Code Playgroud)

谢谢!

And*_* D. 5

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

if (x < 3) /* action */;
Run Code Online (Sandbox Code Playgroud)

被翻译成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:
  // ...
Run Code Online (Sandbox Code Playgroud)

现在考虑这段代码:

if (x == 3) /* action */;
Run Code Online (Sandbox Code Playgroud)

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

  cmp %eax, 3
  jne @@skip // < -- here is the only difference
  /* action is run when x is equal to 3 */
@@skip:
  ...
Run Code Online (Sandbox Code Playgroud)

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

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

  • +1为好,详细,最重要的是,正确答案! (3认同)