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