这是一位高级经理在面试时问的问题。

哪个更快?

while(1) {
    // Some code
}

or

while(2) {
    //Some code
}

我说过两者具有相同的执行速度,因为while中的表达式最终应求值为true或false。在这种情况下,两者都求值为true,并且while条件中没有额外的条件指令。因此,两者将具有相同的执行速度,我更喜欢while(1)。

但面试官自信地说: “检查你的基本知识。While(1)比While(2)快。” (他不是在试探我的信心)

这是真的吗?

请参见:“for(;;)”是否比“while (TRUE)”快?如果不是,人们为什么要使用它?


当前回答

这取决于编译器。

如果它优化了代码,或者对于一个特定的指令集,如果它用相同数量的指令计算1和2为真,那么执行速度将是相同的。

在实际情况下,它总是同样快,但可以想象在特定的编译器和特定的系统中,这将得到不同的计算。

我的意思是:这不是一个与语言(C)相关的问题。

其他回答

显而易见的答案是:正如所发布的,两个片段将运行一个同样繁忙的无限循环,这使得程序无限慢。

虽然从技术上讲,将C关键字重新定义为宏将具有未定义的行为,但这是我能想到的使任何一个代码片段快速的唯一方法:你可以在两个片段之上添加这一行:

#define while(x) sleep(x);

它确实会使while(1)比while(2)快一倍(或慢一半)。

在我看来,这是一个被伪装成技术问题的行为面试问题。有些公司会这样做——他们会问一个任何有能力的程序员都应该很容易回答的技术问题,但是当面试者给出正确答案时,面试官会告诉他们他们错了。

公司想看看你在这种情况下会作何反应。你是否会因为自我怀疑或害怕让面试官不高兴而安静地坐在那里,不强调自己的答案是正确的?或者你愿意挑战一个你知道是错误的权威人士吗?他们想看看你是否愿意坚持自己的信念,以及你是否能以一种机智和尊重的方式做到这一点。

我能想到为什么while(2)会更慢的唯一原因是:

代码将循环优化为 2 . CMP eax 当减法发生时,你实际上是在减法 A. 00000000 - 00000010 CMP eax, 2 而不是 B. 00000000 - 00000001 CMP eax, 1

CMP只设置标志,不设置结果。所以对于最低有效位,我们知道b是否需要借位,而对于a,你必须做两次减法才能得到借位。

是的,对于人类来说,while(1)比while(2)快得多!如果我在一个不熟悉的代码库中看到while(1),我立即知道作者的意图,我的眼球可以继续看下一行。

If I see while(2), I'll probably halt in my tracks and try to figure out why the author didn't write while(1). Did the author's finger slip on the keyboard? Do the maintainers of this codebase use while(n) as an obscure commenting mechanism to make loops look different? Is it a crude workaround for a spurious warning in some broken static analysis tool? Or is this a clue that I'm reading generated code? Is it a bug resulting from an ill-advised find-and-replace-all, or a bad merge, or a cosmic ray? Maybe this line of code is supposed to do something dramatically different. Maybe it was supposed to read while(w) or while(x2). I'd better find the author in the file's history and send them a "WTF" email... and now I've broken my mental context. The while(2) might consume several minutes of my time, when while(1) would have taken a fraction of a second!

我有点夸张,但也只是一点点。代码的可读性非常重要。这一点在面试中很值得一提!

我认为线索可以从“高级经理的询问”中找到。这个人显然在成为经理后就停止了编程,然后他/她花了几年时间才成为高级经理。从未失去对编程的兴趣,但从那以后再也没有写过一行字。所以他提到的并不是“任何一个像样的编译器”,而是“这个人在二三十年前合作过的编译器”。

At that time, programmers spent a considerable percentage of their time trying out various methods for making their code faster and more efficient as CPU time of 'the central minicomputer' was so valueable. As did people writing compilers. I'm guessing that the one-and-only compiler his company made available at that time optimized on the basis of 'frequently encountered statements that can be optimized' and took a bit of a shortcut when encountering a while(1) and evaluated everything else, including a while(2). Having had such an experience could explain his position and his confidence in it.

让你被录用的最好方法可能是,在你顺利地引导他进入下一个面试主题之前,让高级经理忘乎所以地给你讲2-3分钟“编程的美好时光”。(好的时机在这里很重要——太快你会打断故事——太慢你会被贴上焦点不集中的标签)。一定要在面试结束时告诉他,你对这个话题非常感兴趣。