Nowadays I do some optimize work in java, and got an interesting(?) question.
My test environment is jdk 1.8 and Windows 10 and with intellij 2018.1. And there is a test-code below.
int count = 1000000;
int listSize = 10;
{
// case 1
List<Integer> list = new ArrayList<>(listSize);
long start = System.nanoTime();
for (int i = 0; i < count; i++) {
for (int j = 0; j < listSize; j++) {
list.add(j);
}
}
long end = System.nanoTime();
long result = end - start;
System.out.println("Result: " + result);
}
{
// case 2
List<Integer> list = new ArrayList<>(listSize);
long start = System.nanoTime();
for (int i = 0; i < count; i++) {
list.add(0);
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
}
long end = System.nanoTime();
long result = end - start;
System.out.println("Result: " + result);
}
And the result is
Result: 134686088 Result: 183671342
And my question is Why is there the performance difference between the above two codes? With the visual studio on c++, i remember the compiler(visual studio) optimize two case to same machine language.
Anyone could help me? and tell me the best way(best performance) with java loop programming.
Thx.