【问题标题】:In Android, why the first adding code is slower than second adding code?在Android中,为什么第一次添加代码比第二次添加代码慢?
【发布时间】:2016-01-10 10:13:54
【问题描述】:

我正在使用面向 Android API 18 的 Android Studio 1.5.1(在 Android KitKat 4.4 之前,所以我处理的是 Dalvik,而不是 ART 运行时)。

似乎当我在不使用变量的情况下添加 10 个整数并再次使用变量添加相同的数字时,无论我是否使用变量,第一个代码总是比第二个代码慢。

例如,在下面的代码中:

第一个代码用 //****First code**** 标记,不使用变量添加 10 个整数,而第二个代码用 //****Second code** 标记**,添加相同的 10 个整数,但它使用 10 个变量。

与不使用变量相比,不使用变量是否应该会减慢代码执行速度?

此外,如果我交换代码,如果我将 //****Second 代码**** 移到 //****First 代码**** 上方,则 //****Second code**** 现在变得比 //****First code**** 慢。

我的问题是:

为什么无论是否使用变量,第一个代码总是比第二个代码慢?

long start, end, elapsed;

    //****First code****

    start = System.nanoTime();
    System.out.printf("The sum is %d\n", (0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9));
    end = System.nanoTime();
    elapsed =  end - start;
    System.out.println("start=" + start + " end=" + end + " elapsed=" + elapsed);

    //****Second code****

    start = System.nanoTime();
    int     a0=0,
            a1=1,
            a2=2,
            a3=3,
            a4=4,
            a5=5,
            a6=6,
            a7=7,
            a8=8,
            a9=9;

    a1 += a0;
    a2 += a1;
    a3 += a2;
    a4 += a3;
    a5 += a4;
    a6 += a5;
    a7 += a6;
    a8 += a7;
    a9 += a8;

    System.out.printf("The sum is %d\n", a9);
    end = System.nanoTime();
    elapsed =   end - start;
    System.out.println("start="+start + " end="+end +" elapsed="+elapsed);

【问题讨论】:

    标签: java android performance dalvik


    【解决方案1】:

    您正在计算在 printf 中花费的时间。这应该会给出更多类似的结果。尽管线程可能随时进入睡眠状态,但不能保证它是相同的。此外,在第一种情况下,它将被转换为常量,因此它实际上并没有做任何数学运算。

    long start = System.nanoTime();
    
    //this will be converted to a constant of 45 at compile time
    int total = (0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9);
    long end = System.nanoTime();
    
    System.out.printf("The sum is %d\n", total);
    System.out.println("Time: " + (end - start));
    
    start = System.nanoTime();
    int a0=0,
        a1=1,
        a2=2,
        a3=3,
        a4=4,
        a5=5,
        a6=6,
        a7=7,
        a8=8,
        a9=9;
    total = a0;
    total += a1;
    total += a2;
    total += a3;
    total += a4;
    total += a5;
    total += a6;
    total += a7;
    total += a8;
    total += a9;
    end = System.nanoTime();
    
    System.out.printf("The sum is %d\n", total);
    System.out.println("Time: " + (end - start));
    

    【讨论】:

    • 在第二种情况下它也可能被省略为常数,因为没有外部性
    猜你喜欢
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多