什么是呼叫array.length的成本

问题描述:

在更新for循环为,在每一个我们的应用程序循环,我碰到很多这样的模式来了:

While updating for loops to for-each loops in our application, I came across a lot of these "patterns":

for (int i = 0, n = a.length; i < n; i++) {
    ...
}

而不是

for (int i = 0; i < a.length; i++) {
    ...
}

我可以看到你获得对收藏的性能,因为你不需要调用的尺寸()的方法,每个循环。但随着阵列??

I can see that you gain performance for collections because you don't need to call the size() method with each loop. But with arrays??

于是问题出现了:是 array.length 比普通的可变更为昂贵

So the question arose: is array.length more expensive than a regular variable?

没有,一个呼叫 array.length O(1)或固定时间操作。

No, a call to array.length is O(1) or constant time operation.

由于。长度是(如行为)一个公共 最后 磁盘阵列的成员,它是没有慢不是一个局部变量的访问。 (这是从像来一个方法的调用大小差异很大()

Since the .length is(acts like) a public final member of array, it is no slower to access than a local variable. (It is very different from a call to a method like size())

一个现代化的编译器可能优化调用。长度右行吧。

A modern compiler is likely to optimize the call to .length right out anyway.