哪一个会执行得更快,如果(FLAG == 0)或(0 ==标志)? [英] Which one will execute faster, if (flag==0) or if (0==flag)?
问题描述
面试问题
:哪一个会执行得更快, IF(标志== 0)
或如果(0 ==标志)
?为什么呢?
Interview question
: Which one will execute faster, if (flag==0)
or if (0==flag)
? Why?
推荐答案
我还没有看到任何正确的答案,但(和已经有一些)的警告:纳瓦兹确实指出了用户定义的陷阱。我后悔我匆匆投给予好评的愚蠢的问题,因为它似乎有很多并没有得到它的权利,它提供了有关编译器优化的余地一个很好的讨论:)
I haven't seen any correct answer yet (and there are already some) caveat: Nawaz did point out the user-defined trap. And I regret my hastily cast upvote on "stupidest question" because it seems that many did not get it right and it gives room for a nice discussion on compiler optimization :)
答案是:
什么是的类型?标记
在其中标志
实际上是一个用户定义类型的情况。那就要看 ==操作符的其中超载
被选中。当然,它看起来愚蠢的,他们不会是对称的,但它肯定可以的,我已经看到其他虐待行为。
In the case where flag
actually is a user-defined type. Then it depends on which overload of operator==
is selected. Of course it can seem stupid that they would not be symmetric, but it's certainly allowed, and I have seen other abuses already.
如果标志
是一个内置的,那么这两个应该采取相同的速度。
If flag
is a built-in, then both should take the same speed.
从上 86
文章,我赌注为如果
语句 JXX
指令:也许 JNZ
(跳转如果不是零)或某些等效。
From the Wikipedia article on x86
, I'd bet for a Jxx
instruction for the if
statement: perhaps a JNZ
(Jump if Not Zero) or some equivalent.
我怀疑编译器错过这样一个明显的优化,甚至与优化关闭。这对于窥孔优化是专为事物的类型。
I'd doubt the compiler misses such an obvious optimization, even with optimizations turned off. This is the type of things for which Peephole Optimization is designed for.
编辑:再次兴起,所以让我们添加一些组件(LLVM 2.7 IR)
Sprang up again, so let's add some assembly (LLVM 2.7 IR)
int regular(int c) {
if (c == 0) { return 0; }
return 1;
}
int yoda(int c) {
if (0 == c) { return 0; }
return 1;
}
define i32 @regular(i32 %c) nounwind readnone {
entry:
%not. = icmp ne i32 %c, 0 ; <i1> [#uses=1]
%.0 = zext i1 %not. to i32 ; <i32> [#uses=1]
ret i32 %.0
}
define i32 @yoda(i32 %c) nounwind readnone {
entry:
%not. = icmp ne i32 %c, 0 ; <i1> [#uses=1]
%.0 = zext i1 %not. to i32 ; <i32> [#uses=1]
ret i32 %.0
}
即使一个人不知道如何读的IR,我认为这是自我解释。
Even if one does not know how to read the IR, I think it is self explanatory.
这篇关于哪一个会执行得更快,如果(FLAG == 0)或(0 ==标志)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!