Question

What is the gain, if there is any, from doing this:

for (int i = 0, size = foo.size(); i < size; i++) {}

instead of this:

for (int i = 0 ; i < foo.size(); i++) {}

(foo is a List object)

Was it helpful?

Solution

Well, it means you only evaluate size() once instead of once per iteration. Theoretically, that could be a performance win - it's just possible that computing the size is actually expensive. (For example, you could have a linked list implementation which doesn't remember its size, but actually has to traverse the whole list. Arguably if you find yourself in that situation, the better solution is simply to use a better data structure... if size() is expensive, then access by index is likely to be expensive too.)

In reality, the standard collections have very fast size() methods, so it's usually irrelevant, and harms readability (IMO). Of course, if you don't need the index, it's more readable to use an enhanced for loop anyway...

OTHER TIPS

For the first case size of the List is calculated only once.

For the second case every time the size of List foo is calculated during the itrations.

For me if foo List is of type String i For Each loop

for(String str: foo){

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top