【问题标题】:Is there any advantage to int i = array.length over just calling array.length twice?int i = array.length 比仅仅调用 array.length 两次有什么优势吗?
【发布时间】:2013-12-15 03:38:39
【问题描述】:

在这种情况下将数组的长度放入 int 有什么好处——尽管它可能很小——还是简单地调用 array.length 两倍好?或者编译器优化是否使这些方法等效?

没有整数:

Vector<String> vs = new Vector<String>(a_o.length);
for(int i = 0; i < a_o.length; i++)  {
   vs.add(a_o[i]);
}

int:

int iLen = a_o.length;
Vector<String> vs = new Vector<String>(iLen);
for(int i = 0; i < iLen; i++)  {
   vs.add(a_o[i]);
}

【问题讨论】:

    标签: java arrays optimization compiler-construction


    【解决方案1】:

    AFAIK,一个不错的编译器,编译器会为你做这个优化。
    即使没有,打击也很小。你可能会因为使用Vector 而遭受更多的痛苦。见Why is Java Vector class considered obsolete or deprecated?

    【讨论】:

    • 关于 Vector 的观点。我正在考虑将其更改为 ArrayList,如那里所述。谢谢。
    【解决方案2】:

    编译器很聪明,相信它。它会优化它。

    不要把时间浪费在这样的性能问题上,多关心数据结构等其他事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 2011-07-27
      • 2021-10-25
      相关资源
      最近更新 更多