Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

time complexity or hidden cost of <Array Name>.length in java

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...