【问题标题】:Comparison between for , foreach and iterator: Why the for is faster than for-each in this case?for 、 foreach 和迭代器之间的比较:为什么在这种情况下 for 比 for-each 快?
【发布时间】:2014-05-06 12:54:14
【问题描述】:

我已阅读有关此问题的一些问答,例如thisthisthis。他们中的大多数人说 for-each 并不比 for 慢,在某些情况下甚至更快。

但是我写了下面的代码,结果让我一头雾水。

  public ForWithArraylist() {
    // TODO Auto-generated constructor stub
    for (int i = 0; i < 1000000; i++) {
        number.add(i);
    }
    now = System.currentTimeMillis();
    second = 0;
    third = 0;
}
public void random() {
    for (int i = 0; i < number.size(); i++) {
        int j = number.get(i);
        //second = j;
    }
    second = System.currentTimeMillis();
    System.out.println(second - now);
}
public void it() {
    for (Iterator<Integer> iterator = number.iterator(); iterator.hasNext();) {
        int i = iterator.next();
        //third = i;
    }
    third = System.currentTimeMillis();
    System.out.println(third - second);
}
public void each() {
    for (Integer num : number) {
        int i = num;
    }
    System.out.println(System.currentTimeMillis() - third);
}

我在windows(jdk 6)上运行,结果之一是:

(时间分别为for、iterator和for-each)。 平均而言,“for”比其他两个更快,大约 25 毫秒。

我在 MacBook 上运行,结果之一是:

(时间分别为for、iterator和for-each)。 平均而言,'for' 与 for-each 相同甚至更慢,迭代器最慢。

那么谁能给我解释一下?(IDE、操作系统或其他)

编辑:感谢韦斯顿的提醒,我在另一个窗口(jdk 7)上运行它,我在 MacBook 上也有类似的结果。

【问题讨论】:

  • 一方面,您不能将发现建立在单个测试的基础上,而必须运行一整套测试。
  • Micro-benchmarks 这样可能会让你误入歧途。还有,谎言,该死的谎言和statistics
  • 如果您想要更明确的见解,您可能需要构建所有使用Integer 的循环,然后检查字节码。
  • JDK 1.6 和 JDK 1.7。我知道增强的 for 循环使用数组访问,stackoverflow.com/a/1006425/360211 但也许它也适用于从 1.7 开始的数组访问。

标签: java performance for-loop foreach


【解决方案1】:

您不应该使用 currentTimeMillies() 来测量 CPU 执行时间,因为这种方法会出现意外延迟,而且准确性也较低。 您应该使用 System.nanoTime() 因为首先,它以纳秒为单位,其次,它的值更新更频繁。

此外,您不应该只运行一次时间测量就得出任何结论。 你应该做几次并计算平均值。操作系统有其他业务要处理,不是实时系统。

最后,您必须确保在所有循环中都在执行完全相同的操作。在数组列表上调用“add”方法不仅仅是为数组中的某个位置赋值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2014-09-13
    • 2015-11-10
    • 2022-01-10
    • 2012-08-27
    • 2017-09-26
    • 1970-01-01
    相关资源
    最近更新 更多