这是一位高级经理提出的面试问题。
哪个更快?
while(1) {
// Some code
}
else
while(2) {
//Some code
}
我说这两个执行速度相同,因为里面的表达式while应该最终评估为true或false。在这种情况下,评估true和条件内没有额外的条件指令while。所以,两者都会有相同的执行速度,我更喜欢使用while(1)。
但面试官自信地说:“检查一下你的基础知识,while(1)比起来要快while(2)。” (他没有测试我的信心)
这是真的?
另请参见:“for(;;)”比“while(TRUE)”更快?如果没有,为什么人们使用它?
喜欢这个:
people = []
begin
info = gets.chomp
people += [Person.new(info)] if not info.empty?
end while not info.empty?
该begin <code> end while <condition>由Ruby的作者Matz的拒绝。相反,他建议使用Kernel#loop,例如
loop do
# some code here
break if <condition>
end