Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 932
Dziugas Avatar asked Dec 16 '14 17:12

Dziugas


1 Answers

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) {
   ...
} 
like image 176
Maroun Avatar answered Oct 07 '22 23:10

Maroun