2

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();
}
3
  • Another thing: there's a good chance that you should be using ArrayList instead of Vector. Vector is synchronized - it's safe to modify from multiple threads, but if you're not doing that, then the synchronization just adds overhead. Commented Apr 18, 2011 at 16:02
  • Will keep this in mind for the future. Thanks. Commented Apr 18, 2011 at 16:07
  • Yes, Vector is very old school, common in the late 90s. Commented Apr 18, 2011 at 16:26

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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) {
    ...
}

?

2 Comments

I've never seen this syntax. Could you provide a link to its documentation?
@Alex, this is a called the "enhanced for loop" and was introduced in Java 5.
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.