开发者

Preferred Way to Reuse Variable in a Loop in Java

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

开发者_StackOverflowVector section = null;

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


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

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

?


If you don't use section outside the loop then your first style would be preferable.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜