I am using Android Studio 1.5.1 targeting Android API 18 (before Android KitKat 4.4, so I’m dealing with Dalvik, not ART runtime).
It seems that when I add 10 integer numbers without using variables and again adding the same numbers using variables, the first code is always slower than the second code regardless if I use variables or not.
For example, in the code below:
The first code, which is labeled with //****First code****, adds 10 integers numbers without using variables whereas the second code, which is labeled with //****Second code****, adds the same 10 integer numbers but it uses 10 variables.
Should not using variables slow down the code execution compared to the one that does not use variables?
Moreover, if I swap the codes, if I move the //****Second code**** above the //****First code****, the //****Second code**** now becomes slower than //****First code****.
My question is:
Why the first code is always slower than the second code regardless if it uses variables or not?
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);
You are counting time spent in printf. This should give more similar results. It isn't guaranteed for it to be the same though as the thread might go to sleep at any time. Also, in the first case it will be converted to a constant so it doesn't really do any math.
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));