java constant loop performance optimization

Alperen Üretmen :

I have 2 pieces of code:

First one:

List<Integer> integers = new ArrayList<>();
integers.add(0);
integers.add(1);
//Assume that list will always have the same values with loop indices.
//Also any of the methods will not change the size and elements of the list.

for (int i=0;i<integers.size();i++) {

    if (0 == integers.get(i)) {
        foo();
    }
    else if (1 == integers.get(i)) {
        bar();
    }
}

Second one:

foo();
bar();

I know both code snippets are doing the same thing but is there any difference in performance or does JVM doing something to optimize the first snippet in compile time or runtime?

Hulk :

The compiler/JIT won't be able to do much for the first snippet.

It cannot prove that successive calls to integers.get(i) will always yield the same result, so it is not allowed to reuse the result of the first call, and it cannot even tell that one of foo() or bar() will always be executed.

The code appears simple enough for humans, but the compiler would have to make assumptions about the implementation of ArrayList that will be loaded at runtime, and it will not do that.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=133176&siteId=1