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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With