1

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.

Kebron
  • 23
  • 4
  • thx. i will check the link. – Kebron Jun 14 '18 at 00:56
  • it could be the second iterator to be checked each time while processing the list. in any case could not be much scalable writing by hand each iteration if the numbers are big – majik Jun 14 '18 at 00:57

0 Answers0