【问题标题】:Performance wise, is it better to call the length of a given array every time or store the length in a variable and call that variable every time?性能方面,每次调用给定数组的长度还是将长度存储在变量中并每次调用该变量更好?
【发布时间】:2011-07-08 15:39:18
【问题描述】:

我经常调用给定数组的长度,我想知道是否最好继续多次调用它(目前 50 多次,但它一直在增长)还是将长度存储在一个整数并每次都使用该整数。

如果我不清楚我在说什么,请考虑以下几点:

我有一个字符串数组:

String[] str = new String[500]; //The length is actually dynamic, not static

当然,我在其中添加了一些值,但我在整个应用程序中一直调用字符串的长度:

int a = str.length;
int b = str.length;
int c = str.length;
int d = str.length;
int e = str.length;

等等......那么这样做更好吗:(性能方面,不要太关心内存)

int length = str.length;
    int a = length;
    int b = length;
    int c = length;
    int d = length;
    int e = length;

谢谢。

【问题讨论】:

  • 尝试测量它。您会发现检索一个属性的值 50 次,甚至几千次,甚至都无法衡量。
  • “长度是动态的”是什么意思? Java 中没有动态数组。
  • 我认为他的意思是它在编译时不知道(即他不能到处使用 500)。
  • 这就是我的意思。

标签: java performance


【解决方案1】:

没有区别。访问数组长度时不调用方法。您只需阅读一个内部字段。即使你调用了一个方法,在当前的 JVM 中差异也可以忽略不计。

【讨论】:

  • +1:像 String.length() 这样的方法被内联,所以即使它们也没有区别。
  • 感谢您的澄清。这是有道理的。
【解决方案2】:

array.length 是访问数组对象中的一个字段,所以应该不会对性能产生任何影响。

【讨论】:

    【解决方案3】:

    你觉得哪个会让代码更清晰?

    JVM 很可能会优化代码来做同样的事情。即使没有,差异也可能小于 1 纳秒。

    【讨论】:

      猜你喜欢
      • 2011-03-23
      • 2013-08-02
      • 2011-01-11
      • 2020-02-14
      • 2016-01-27
      • 2016-06-27
      • 2019-01-24
      • 1970-01-01
      • 2021-08-06
      相关资源
      最近更新 更多