时间复杂度或&LT隐性成本;数组名称&gt;。长度在java中 [英] time complexity or hidden cost of <Array Name>.length in java
问题描述
我看着在Java中的一个项目,发现上面写着象下面这样为
循环:
的for(int i = 1; I&LT;则为a.length;我++)
{
...........
...........
...........
}
我的问题是:这是昂贵的计算则为a.length
(这里是数组名)?如果没有那么如何则为a.length
是越来越内部计算(指JVM如何确保O(1)访问此)?是类似于:
INT长度=则为a.length;
的for(int i = 1; I&LT;长度;我+ +)
{
...........
...........
...........
}
即。像访问函数中的局部变量的值。谢谢你。
我的问题是:这是昂贵的计算则为a.length
块引用>没有。这只是一个外地在阵列上(见 JLS节10.7 一>)。这不是昂贵的,和JVM知道它永远不会改变,可以适当优化循环。 (事实上,我所期望的良好的JIT注意到初始化的变量与非负数的正常模式,检查它的小于
长度
,然后访问阵列 - 如果注意到,就可以删除数组边界检查。)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 howa.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.
解决方案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.)这篇关于时间复杂度或&LT隐性成本;数组名称&gt;。长度在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!