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

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

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 reevaluated? Wouldn't it be more effective?

 int[] array = {5, 10, 15}; int noOfElements = array.length; for(int i = 0; i < noOfElements; i++) { //do something with array[i] } 

Thus, (as far as I know), the program only needs to calculate it, and then look at the value of the noOfElements variable.

Note. I know the extended for loop, but you can't use it if you want to use a variable that increments ("i" in this example) to achieve other things inside the loop.

I suspect that in fact it is about whether the Java compiler has the ability to realize that "array.length" does not change and actually reuses this value after calculating it once.

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

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

This means that the operator array.length has nothing to do with the calculation; it refers only to an instance variable.

Thanks for the input guys!

+6
source share
3 answers

See JLS- 10.7. Members of the array :

Array type elements are as follows:

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

The call to array.length is O (1) (constant time is a final member).

Also note that, as mentioned in the comments, the β€œtraditional” way is not necessarily the way you suggested. You can use for each cycle :

 for(int i : array) { ... } 
+8
source

length is a field; therefore, it is not calculated when considering the condition of the cycle loop.

In your second block of code, you enter a field to represent the length, which increases memory usage (a bit, but still an important factor).

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

+2
source

length is an array field that is not calculated if you call myArray.length , instead it is set when the array is created. Thus, no, it is no more efficient to store it in a variable before starting the for() loop.

+1
source

Source: https://habr.com/ru/post/979720/


All Articles