Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the advantage of declaring variable in for

Tags:

java

for-loop

I saw the following code on the Android support Library:

for (int i = 0, z = getChildCount(); i < z; i++)

What's the advantage to use z = getChildCount instead of just i < getChildCount() ?

like image 769
Guilherme Torres Castro Avatar asked May 25 '16 22:05

Guilherme Torres Castro


2 Answers

Declaring multiple variables inline is a questionable style, but the assignment calculates the count once at the beginning of the loop and saves the value. If the operation is expensive, it prevents spending time computing it on each iteration.

like image 87
chrylis -cautiouslyoptimistic- Avatar answered Oct 15 '22 12:10

chrylis -cautiouslyoptimistic-


In a for-loop, it can be broken into 3 parts:

for(initialization ; terminating condition ; increment){

}

In the for-loop, the initialization will be run only once. But the terminating condition will be checked in every iteration. Hence if you write the for loop as:

for (int i = 0; i<count(); i++){
}

count() method will run every iteration.

Writing it as below ensures count() will only be invoked once and the reason for that of course would be cutting down the unnecessary invoking of count().

for (int i = 0, z = count(); i < z; i++)

The above is also equivalent to writing it as (except that z is now outside the scope of the loop):

int z = count();
for (int i = 0; i < z; i++)
like image 44
user3437460 Avatar answered Oct 15 '22 12:10

user3437460