调用 array.length 的成本是多少 [英] What is the Cost of Calling array.length

查看:27
本文介绍了调用 array.length 的成本是多少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的应用程序中将 for 循环更新为 for-each 循环时,我遇到了很多这样的模式":

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++) {
    ...
}

我可以看到您获得了集合的性能,因为您不需要在每个循环中调用 size() 方法.但是用数组??

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.

由于 .length 是(行为)一个 public final 成员 array,它不是访问速度比局部变量慢.(这与调用size()这样的方法有很大不同)

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

现代 JIT 编译器很可能会立即优化对 .length 的调用.

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

您可以通过查看 OpenJDK 中 JIT 编译器的源代码或让 JVM 转储出 JIT 编译的本机代码并检查代码来确认这一点.

You can confirm this by either looking at the source code of the JIT compiler in OpenJDK, or by getting the JVM to dump out the JIT compiled native code and examining the code.

注意,可能存在JIT编译器做不到这一点的情况;例如

Note that there may be cases where the JIT compiler can't do this; e.g.

  1. 如果您正在调试封闭方法,或者
  2. 如果循环体有足够的局部变量来强制寄存器溢出.

这篇关于调用 array.length 的成本是多少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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