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

哪个更快?

while(1) {
    // Some code
}

or

while(2) {
    //Some code
}

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

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

这是真的吗?

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


当前回答

等一下。面试官长得像这个人吗?

面试官自己没能通过面试已经够糟糕的了, 如果这家公司的其他程序员已经“通过”了这个测试呢?

不。求值语句1 == 0和2 == 0应该同样快。我们可以想象,在糟糕的编译器实现中,一个可能比另一个快。但是,没有充分的理由说明其中一个应该比另一个快。

即使在某些模糊的情况下,这种说法是正确的,也不应该基于模糊(在这种情况下,令人毛骨悚然)琐事的知识来评估程序员。不要担心这次面试,最好的办法就是走开。

免责声明:这不是原创呆伯特漫画。这只是一个混搭。

其他回答

关于这个问题的另一个答案是,看看你是否有勇气告诉你的经理他/她错了!以及你能多温柔地交流。

我的第一直觉是生成汇编输出,向管理器显示任何像样的编译器都应该照顾它,如果它不这样做,你将提交它的下一个补丁:)

看到这么多人深入研究这个问题,正好说明了为什么这可以很好地作为一个测试,看看您想要多快地进行微优化。

我的答案是;这并不重要,我更关注我们正在解决的业务问题。毕竟,这就是我的工作。

此外,我会选择while(1){},因为它更常见,其他队友不需要花时间去弄清楚为什么有人会选择比1更高的数字。

现在去写一些代码。: -)

它们是相等的。

根据规范,任何不为0的都被认为是真的,所以即使没有任何优化,一个好的编译器也不会生成任何代码 For while(1) or while(2)。编译器将生成一个简单的检查!= 0。

是的,对于人类来说,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!

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

You should have asked him how did he reached to that conclusion. Under any decent compiler out there, the two compile to the same asm instructions. So, he should have told you the compiler as well to start off. And even so, you would have to know the compiler and platform very well to even make a theoretical educated guess. And in the end, it doesn't really matter in practice, since there are other external factors like memory fragmentation or system load that will influence the loop more than this detail.