What is the runtime environment of array.length?

Let's say I have an array:

int[] array = new int[10];

What is the execution time:

int len = array.length;

I would have thought it would be a constant operation of the time, but today in an interview the interviewer told me that it would be O(n)because the number of elements would need to be calculated.

Also, if I have a loop like this:

for (int i = array.length - 1; i >=0; i--) {
    something with array[i];
}

Is it due to additional operations nto get to the end of the array in order to start the loop? The interviewer came from the C-background, so maybe they were wrong about how Java works, but I didn’t want to push it during the interview.

+4
source share
3 answers

array.length is O (1), and the O (n) cycle as a whole (provided that "something" is a constant time).

Difference for c?

C , , , O(1) . " " , .

( , , , .)

+9

SO, array.length:

Java?

length - O (1), , .

, , O (n).

0

JAVA, JVM ( IndexOutOfBoundsException, ).

It might be a good idea to cache the length of the array in a local variable because accessing the JVM glass is faster, but this improvement is very small, usually looping the loop will be overweight for this optimization.

0
source

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


All Articles