This is the result of your code on my machine:
1st run:
code block (has Long array) 1 = 6070325
code block (has long array) 2 = 8739868
2nd run:
code block (has Long array) 1 = 4449868
code block (has long array) 2 = 6224883
3rd run:
code block (has Long array) 1 = 5773081
code block (has long array) 2 = 1160343
I think that your benchmark is badly designed.
And if we change the code to this:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Benchmark " + (i + 1));
benchmark();
System.out.println();
}
}
public static void benchmark() {
long startTime;
long endTime;
Long a[] = new Long[10000];
long b[] = new long[10000];
for (int i = 0; i < a.length; i++)
a[i] = 12l;
for (int i = 0; i < b.length; i++)
b[i] = 12l;
//code block 1
startTime = System.nanoTime();
Arrays.sort(a);
endTime = System.nanoTime();
System.out.println("\tcode block (has Long array) 1 = " + (endTime - startTime));
//code block 2
startTime = System.nanoTime();
Arrays.sort(b);
endTime = System.nanoTime();
System.out.println("\tcode block (has long array) 2 = " + (endTime - startTime));
}
}
We can see the result you said. This is because of compare method difference in long
data type and Long
object. You know that the long
is a primitive data type but Long
is an object. So, to comparing two long value, system can compare them without using any complicated compare method but for comparing two Long
object, JVM should use the compare method of Long
object and that method takes more time.
Note that this is the result of 2nd code:
Benchmark 1
code block (has Long array) 1 = 2957778
code block (has long array) 2 = 751911
Benchmark 2
code block (has Long array) 1 = 2081759
code block (has long array) 2 = 392857
Benchmark 3
code block (has Long array) 1 = 2031473
code block (has long array) 2 = 410946
Benchmark 4
code block (has Long array) 1 = 2016387
code block (has long array) 2 = 360241
Benchmark 5
code block (has Long array) 1 = 2070235
code block (has long array) 2 = 360870
Benchmark 6
code block (has Long array) 1 = 2105156
code block (has long array) 2 = 360801
Benchmark 7
code block (has Long array) 1 = 2020928
code block (has long array) 2 = 386013
Benchmark 8
code block (has Long array) 1 = 1976229
code block (has long array) 2 = 359682
Benchmark 9
code block (has Long array) 1 = 5213093
code block (has long array) 2 = 363664
Benchmark 10
code block (has Long array) 1 = 3999880
code block (has long array) 2 = 361638