我使用的是Android Studio 1.5.1,目标是Android API 18(在Android KitKat 4.4之前,所以我使用的不是ART运行时,而是Dalvik)。
似乎当我在不使用变量的情况下添加10个整数,并再次使用变量添加相同的数字时,无论我是否使用变量,第一个代码总是比第二个代码慢。
例如,在下面的代码中:
第一个代码被标记为//***第一个代码***,在不使用变量的情况下添加10个整数,而第二个代码被标签为//***第二个编码***,添加相同的10个整数但使用10个变量。
与不使用变量的代码相比,不使用变量是否应该降低代码执行速度?
此外,如果我交换代码,如果我将//***第二个代码***移动到//***第一个代码***之上,//***第三个代码***现在变得比//***第一代码***慢。
我的问题是:
为什么不管是否使用变量,第一个代码总是比第二个代码慢?
long start, end, elapsed;
//****First code****
start = System.nanoTime();
System.out.printf("The sum is %dn", (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 %dn", 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 %dn", 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 %dn", total);
System.out.println("Time: " + (end - start));