时间复杂度或&LT隐性成本;数组名称>。长度在java中 [英] time complexity or hidden cost of <Array Name>.length in java

查看:134
本文介绍了时间复杂度或&LT隐性成本;数组名称>。长度在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看着在Java中的一个项目,发现上面写着象下面这样循环:

 的for(int i = 1; I<则为a.length;我++)
{
    ...........
    ...........
    ...........
}

我的问题是:这是昂贵的计算则为a.length (这里是数组名)?如果没有那么如何则为a.length 是越来越内部计算(指JVM如何确保O(1)访问此)?是类似于:

  INT长度=则为a.length;
的for(int i = 1; I<长度;我+ +)
{
    ...........
    ...........
    ...........
}

即。像访问函数中的局部变量的值。谢谢你。


解决方案

  

我的问题是:这是昂贵的计算则为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 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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆