java中<Array Name>.length的时间复杂度或隐藏成本 [英] time complexity or hidden cost of <Array Name>.length in java
问题描述
我在看一个 java 项目,发现了一个 for
循环,它的写法如下:
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++)
{
...........
...........
...........
}
我的问题是:计算 a.length
(这里 a 是数组名)的成本高吗?如果没有,那么 a.length
是如何在内部计算的(意味着 JVM 如何确保 O(1) 访问这个)?类似于:
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.
推荐答案
我的问题是:计算 a.length 的成本高吗
My question is: is it costly to calculate the a.length
没有.它只是数组上的一个字段(参见 JLS 第 10.7 节).它并不昂贵,并且 JVM 知道它永远不会改变并且可以适当地优化循环.(确实,我希望一个好的 JIT 注意到用非负数初始化变量的正常模式,检查它是否小于 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.)
这篇关于java中<Array Name>.length的时间复杂度或隐藏成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!