Dziugas
Dziugas

Reputation: 1570

Is there a difference in runtime efficiency if I evaluate the size of the array outside the loop?

The traditional way to iterate over an (integer, in this example) array of elements is the following:

int[] array = {5, 10, 15};

for(int i = 0; i < array.length; i++) [
    //do something with array[i]
}

However, does this mean that after each iteration 'array.length' is re-evaluated? Would it not be more efficient to do this? :

int[] array = {5, 10, 15};

int noOfElements = array.length;

for(int i = 0; i < noOfElements; i++) {
    //do something with array[i]
}

In this way, (to my understanding) the program only has to calculate it once and then look up the value of 'noOfElements' variable.

Note: I am aware of the enhanced for-loop, but it cannot be used when you want to use the variable that is being incremented ('i' in this example) to achieve other things within the for-loop.

I'm suspecting that this is actually a question of whether the Java compiler has the capability of realising that 'array.length' doesn't change and actually reusing that value after calculating it once.

So my question is: Is there a difference in runtime efficiency of the first block of code I wrote and the second one?

What I gather from the replies below, is that when an array is instantiated (is that the right word?) an instance variable called length is created and it is equal to the number of elements in the array.

What this means is that the statement array.length has nothing to do with calculation; it is only referencing the instance variable.

Thanks for the input guys!

Upvotes: 6

Views: 137

Answers (3)

Maroun
Maroun

Reputation: 95968

See JLS- 10.7. Array Members:

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.

Calling array.length is O(1) (constant time operation - it's final member of the array).

Also note that as mentioned in the comments, "traditional" way is not necessarily the way you proposed. You can use for-each loop:

for(int i : array) {
   ...
} 

Upvotes: 8

Dave
Dave

Reputation: 591

length is a field, therefore is not calculated when examining the for loop condition.

Your second block of code introduces a field to represent the length, thus increases memory usage (slightly, but still an important factor).

Yet further, if the array were to be re-created/re-assigned at some point, with a different set of values, your field would not be updated, but the array's length field would.

Upvotes: 2

Marv
Marv

Reputation: 3557

length is a field of an array that is not being calculated if you call myArray.length, instead it is being set when you create the array. So no, it's not more efficient to save it to a variable before starting the for() loop.

Upvotes: 1

Related Questions