What is the advantage of declaring a variable for

In the Android support library, I saw the following code:

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

What is the advantage of using z = getChildCount instead of just i < getChildCount() ?

+5
source share
2 answers

Declaring several inline variables is a dubious style, but the job calculates the counter once at the start of the loop and stores the value. If the operation is expensive, it does not allow you to spend time calculating it at each iteration.

+8
source

In a loop, it can be divided into 3 parts:

 for(initialization ; terminating condition ; increment){ } 

In for-loop, initialization will only be performed once. But the termination condition will be checked at each iteration. Therefore, if you write a for loop like:

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

count () will run every iteration.

By writing it as shown below, count() will be called only once, and the reason for this, of course, will reduce the unnecessary call to count ().

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

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

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

All Articles