time complexity or hidden cost of <Array Name>.length in java
arrays, complexity-theory, java
Solution
My question is: is it costly to calculate the a.length
No. It's just a field on the array (see JLS section 10.7). It's not costly, and the JVM knows it will never change and can optimize loops appropriately. (Indeed, I would expect a good JIT to notice the normal pattern of initializing a variable with a non-negative number, check that it's less than `length` and then access the array - if it notices that, it can remove the array boundary check.)
Problem
I was looking at a project in java and found a `for` loop which was written like below: ``` for(int i=1; i<a.length; i++) { ........... ........... ........... } ``` My question is: is it costly to calculate the `a.length` (here a is array name)? if no then how `a.length` is getting calculated internally (means how JVM make sure O(1) access to this)? Is is similar to: ``` int length = a.length; for(int i=1; i<length; i++) { ........... ........... ........... } ``` i.e. like accessing a local variable's value inside the function. Thanks.