2
        for (int i = 0; i < array.length; ++i) {
            do something referencing array[i]
            do something referencing array[i]
            ....
        }

currentValue = array[i]在这样的代码中,设置一个类似的变量然后引用它而不是真的有用array[i]吗?我觉得编译器会足够聪明,可以做这样的事情并使这样的代码变得毫无意义。

4

1 回答 1

4

If you read the byte code that the compiler generates you will see that it does no such optimization. This means that in interpreted mode the array lookup will be done every time. If the method with the loop runs enough many times the JIT compiler will have another look at it and may optimize it.

Conclusion: if you want predictable results, store the array element in a local variable. More importantly, that way the code becomes more readable too.

于 2013-07-15T21:22:11.363 回答