5

In my code,

for(City city : country.getCities()){
   // do some operations
}

Using country.getCities() is costly? Will JVM maintain the stacktrace for every call..?

List<City> cityList = country.getCities();
for(City city : cityList){
   // do some operations
}

What is the best way to use?

5 Answers 5

9

No, this loop:

for(City city : country.getCities())

will only call country.getCities() once, and then iterate over it. It doesn't call it for each iteration of the loop. In your case it's equivalent to:

for (Iterator<City> iterator = country.getCities().iterator();
     iterator.hasNext(); ) {
    City city = iterator.next();
    // do some operations
}

There's no benefit in rewriting it as per your second snippet.

See section 14.14.2 of the JLS for more details.

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

2 Comments

There is one benefit, writing the long version with an explicit iterator allows you to do iterator.remove() which you cannot do with the short version
@portforwardpodcast: Sure, but that's like saying it's better to use a for loop and get because then you've got the index. In the context of the code actually provided here, there's no benefit.
3

In both cases the getCities() is called only once.

Default disclaimer: As always you hardly ever need to worry about performance, as the compiler is much better at it than a person.

Comments

1

These are equivalent. getCities() will only be executed once. (if you stick a System.out.println() in that method you should see this).

Note that it won't call getCities() multiple times not just for reasons of performance, but also because there's no guarantee that it would return the same collection each time (it may be intuitive that it returns the same collection, but not mandated)

I would prefer your first example for conciseness.

Comments

0

Both are same, there is no difference. And country.getCities() will be called once in loop.

I think first one better because there is no extra reference used.

Comments

0

The JVM will optimise the code when its compiled to ensure the country.getCities() method is called once.

You should write your code in the way you and/or your team think is most readable.

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.