在 Java 循环中重用变量的首选方法
以下哪一种是重用 section
向量的首选方式?
Iterator<Vector> outputIter = parsedOutput.iterator();
while(outputIter.hasNext()) {
Vector section = outputIter.next();
}
或者
Vector section = null;
while(outputIter.hasNext()) {
section = outputIter.next();
}
Out of the following, which is the preferred way of reusing the section
vector?
Iterator<Vector> outputIter = parsedOutput.iterator();
while(outputIter.hasNext()) {
Vector section = outputIter.next();
}
or
Vector section = null;
while(outputIter.hasNext()) {
section = outputIter.next();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第二种方式意味着变量
section
在循环外部可见。如果您不在循环之外使用它,则无需这样做,因此请使用第一个选项。就性能而言,不应该有任何明显的差异。The second way means that the variable
section
is visible outside the loop. If you're not using it outside of the loop, then there's no need to do that, so use the first option. As far as performance, there shouldn't be any visible difference.我更喜欢第二个版本,因为循环结束后您的作用域中没有未使用的变量。
然而,那又怎样呢
?
I prefer the second version since you don't have an unused variable in your scope after the loop finishes.
However, what about
?
如果您不在循环外部使用
section
那么您的第一种样式会更好。If you don't use
section
outside the loop then your first style would be preferable.直觉上我会选择你的解决方案的第二种变体。但最终它很大程度上取决于优化器,无论如何它都可能会改变你的代码。尝试编译您的代码,然后查看生成的字节码以了解发生了什么。您可以使用 javap 查看生成的内容或任何其他可用的反编译器。
最后,即使如此,代码也可能在运行时以另一种方式进行优化。
Intuitively I'd choose the second variant of your solution. But finally it pretty much depends on the optimizier, it might change your code anyway. Try to compile your code and then look at the generated bytecodes to see what happened. You can use javap to see what is generated or any other available decompiler.
Finally even then the code might be optimized in even another way during runtime.