简体   繁体   English

Java编译器是否优化了数组索引查找?

[英]Does Java compiler optimize array index lookups?

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

In code such as this, is it actually useful to set a variable like currentValue = array[i] and then reference that instead of array[i] ? 在像这样的代码中,设置一个像currentValue = array[i]这样的变量然后引用而不是array[i]是否真的很有用? I feel like the compiler would be smart enough to do something like that and render such code pointless. 我觉得编译器足够聪明,可以做类似的事情并使这些代码变得毫无意义。

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. 如果循环的方法运行了很多次,那么JIT编译器将再次查看它并可以优化它。

Conclusion: if you want predictable results, store the array element in a local variable. 结论:如果需要可预测的结果,请将数组元素存储在局部变量中。 More importantly, that way the code becomes more readable too. 更重要的是,这样代码也变得更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM