分支语句:在 for/while 循环中中断或返回更好?
显然只有在方法可以立即退出的情况下才用 return
for (...) {
return;
}
或者
for () {
break;
}
哪个更好?
Obviously with return only in the case that the method can immediately exit
for (...) {
return;
}
or
for () {
break;
}
Which is better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您给出的两个示例并不完全相同,因此很难说哪种风格更好。这里有两种方法,它们的作用稍微相似:
对比:
在这种情况下,我推荐第一种,因为它简单得多。不太可能存在显着的性能差异。有些人更喜欢第二种,因为他们只希望每个函数中有一个返回,但我认为遵守该规则并不总是一个好主意。有时多个 return 语句会让事情变得更加清晰。
The two examples you gave aren't exactly equivalent so it's a little difficult to say which is better style. Here are two approaches that are slightly more similar in what they do:
Versus:
In this case I'd recommend the first because it's much simpler. It is unlikely that there is a significant performance difference. Some people prefer the second because they only want a single return in each function, but I don't think it is always a good idea to stick to that rule. Sometimes multiple return statements makes things much clearer.
我宁愿建议采用中断方法。看起来代码更多,但更容易理解。此外,以后进行更改也更容易。为了清楚起见,您可以使用带标签的循环。
I would rather suggest the break approach. It looks like more code but is easier to understand. Also, making changes later is easier. You can go for labeled loops for clarity.
您已经回答了自己的问题。这两者具有不同的语义,并且不能真正互换,并且
return
变体仅适用于更具体的场景......因此正是在这些特定场景中,您应使用
return
变体。意图是显而易见的,因此具有更好的可读性。如果在return
就足够的情况下使用break
,那么读者必须花费更多时间来弄清楚break
后会发生什么。当没有发生任何重大事件时,return
会很快更清楚地传达这一点。You've answered your own question. These two have different semantics and aren't really interchangeable, and the
return
variant is applicable only to more specific scenarios......thus precisely in those specific scenarios you should use the
return
variant. The intention is immediately obvious and thus it makes for better readability. If you use abreak
whenreturn
suffices, then the reader must spend more time to figure out what happens after thebreak
. When nothing significant happens, areturn
would've quickly conveyed this much more clearly.