简体   繁体   English

在Java中重用循环中变量的首选方法

[英]Preferred Way to Reuse Variable in a Loop in Java

Out of the following, which is the preferred way of reusing the section vector? 出于以下情况,这是重用section向量的首选方法?

Iterator<Vector> outputIter = parsedOutput.iterator();

while(outputIter.hasNext()) {
    Vector section = outputIter.next();
}

or 要么

Vector section = null;

while(outputIter.hasNext()) {
    section = outputIter.next();
}

The second way means that the variable section is visible outside the loop. 第二种方式意味着变量section在循环外部可见。 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 但是,怎么样

for (Vector section: parsedOutput) {
    ...
}

?

如果你不使用循环外的section ,那么你的第一种风格会更好。

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. 您可以使用javap查看生成的内容或任何其他可用的反编译器。

Finally even then the code might be optimized in even another way during runtime. 最后,即使这样,代码也可能在运行时以其他方式进行优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM