java - 使用增强的 For 循环语法输出较慢的结果

标签 java android

当我看到这篇文章时,我正在阅读 Google 文档页面 http://developer.android.com/training/articles/perf-tips.html

谁能解释为什么我得到相反的结果?

我的结果是:(平均) 结果 1:76 结果 2:73 结果 3:143

我使用以下代码执行了一些测试(循环执行相同的测试):

package TestPack;

import java.util.ArrayList;


public class Test
{
static ArrayList<Integer> mTheArray = new ArrayList<Integer>();
static
{
    for(int i = 0; i < 10000000; i++)
    {
        mTheArray.add(1234234223);
    }
}

static long mTimeStarted;
public static void main(String args[])
{
    //Test 1.
    mTimeStarted = System.currentTimeMillis();
    One();
    Fn.Out("Result 1: " + String.valueOf(System.currentTimeMillis() - mTimeStarted));

    //Test 2.
    mTimeStarted = System.currentTimeMillis();
    Two();
    Fn.Out("Result 2: " + String.valueOf(System.currentTimeMillis() - mTimeStarted));

    //Test 3
    mTimeStarted = System.currentTimeMillis();
    Three();
    Fn.Out("Result 3: " + String.valueOf(System.currentTimeMillis() - mTimeStarted));

}

//Slowest (But not...).
public static int One()
{
    int sum = 0;
    for (int i = 0; i < mTheArray.size(); ++i) 
    {
        sum += mTheArray.get(i);
    }
    return sum;
}

public static int Two()
{
    int sum = 0;
    ArrayList<Integer> localArray = mTheArray;
    int len = localArray.size();

    for (int i = 0; i < len; ++i) {
        sum += localArray.get(i);
    }
    return sum;
}

//Fastest (But actually slowest in this test).
public static int Three()
{
    int sum = 0;
    for (Integer a : mTheArray) {
        sum += a;
    }
    return sum;
}

最佳答案

您链接的页面明确指出:

With an ArrayList, a hand-written counted loop is about 3x faster (with or without JIT), but for other collections the enhanced for loop syntax will be exactly equivalent to explicit iterator usage.

So, you should use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical ArrayList iteration.

您使用的是 ArrayList,因此您得到的结果似乎与此声明相当一致。

关于java - 使用增强的 For 循环语法输出较慢的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16825618/

相关文章:

java - 如何将我的 Java 代码集成到具有标准 HTML、CSS、Javascript 的 Web 应用程序中?

java - 如何导出和导入sqlite表?

java - 更改符号模式/匹配器中的标签

java - 当Elasticsearch批量操作发生故障时,如何获取文档字段?

安卓 : Error Copying database (Sqliite) From Asset Folder

android - Lateinit 属性 viewModel 尚未初始化

android - 图像尺寸(drawable-hdpi/ldpi/mdpi/xhdpi)

android - 为多个用户管理单个项目的多个订阅

java - 如何防止 AppletClassLoader 在查找类/其他资源时命中服务器?

java客户端消费API