문제

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)

도움이 되었습니까?

해결책

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...

다른 팁

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

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top