簡體   English   中英

在Android中,為什么第一次添加代碼要比第二次添加代碼慢?

[英]In Android, why the first adding code is slower than second adding code?

我正在使用針對Android API 18的Android Studio 1.5.1(在Android KitKat 4.4之前,所以我在處理Dalvik,而不是ART運行時)。

似乎當我在不使用變量的情況下添加10個整數,然后又在使用變量的情況下添加相同的數字時,無論我是否使用變量,第一個代碼總是比第二個代碼慢。

例如,在下面的代碼中:

第一個代碼用// ********第一個代碼****標記,不使用變量就添加10個整數,而第二個代碼用// ********第二個代碼****標記,將相同的10個整數相加,但使用10個變量。

與不使用變量的代碼相比,不使用變量的代碼執行速度會降低嗎?

而且,如果我交換代碼,如果我將// ****第二個代碼****移到// ****第一個代碼****上方,則// ****第二個代碼** **現在比// ********第一個代碼****慢。

我的問題是:

為什么不管是否使用變量,第一個代碼總是比第二個代碼慢?

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);

您正在計算在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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM