这是一位高级经理在面试时问的问题。
哪个更快?
while(1) {
// Some code
}
or
while(2) {
//Some code
}
我说过两者具有相同的执行速度,因为while中的表达式最终应求值为true或false。在这种情况下,两者都求值为true,并且while条件中没有额外的条件指令。因此,两者将具有相同的执行速度,我更喜欢while(1)。
但面试官自信地说:
“检查你的基本知识。While(1)比While(2)快。”
(他不是在试探我的信心)
这是真的吗?
请参见:“for(;;)”是否比“while (TRUE)”快?如果不是,人们为什么要使用它?
是的,对于人类来说,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!
我有点夸张,但也只是一点点。代码的可读性非常重要。这一点在面试中很值得一提!
根据人们花费在测试、证明和回答这个非常直接的问题上的时间和精力来判断,我认为这两者都因为提出这个问题而变得非常缓慢。
所以花更多的时间在这上面…
虽然(2)很荒谬,因为,
While(1)和While (true)在历史上被用于创建一个无限循环,该循环预计在循环中的某个阶段根据一定会发生的条件调用break。
1只是为了总是求值为真,因此,说while(2)和说while(1 + 1 == 2)一样愚蠢,后者也会求值为真。
如果你想完全傻一点,就用:-
while (1 + 5 - 2 - (1 * 3) == 0.5 - 4 + ((9 * 2) / 4.0)) {
if (succeed())
break;
}
我认为面试官犯了一个错别字,这并不影响代码的运行,但如果他故意使用2只是为了表现得奇怪,那么在他把奇怪的语句贯穿你的代码,使其难以阅读和使用之前解雇他。