Guilherme Torres Castro
Guilherme Torres Castro

Reputation: 15350

What the advantage of declaring variable in for

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() ?

Upvotes: 5

Views: 80

Answers (2)

user3437460
user3437460

Reputation: 17454

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

Upvotes: 4

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.

Upvotes: 8

Related Questions