Java优化器和冗余阵列评估 [英] Java optimizer and redundant array evaluations

查看:70
本文介绍了Java优化器和冗余阵列评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有关Java优化的非常基本的问题.

This is a very basic question about the Java optimization.

如果您有一个简单的for循环来遍历数组,并在循环头中使用array.length而不是之前对其进行求值,那么您只需执行一次(这几乎是我经常做的事):

If you have a simple for loop to iterate through an array and use array.length in the header of the loop rather than evaluating it before so that you do it only once (which is what I almost always do):

for(int i=0; i<array.length;i++) { ... }

是否可以优化该语句,以便JVM知道在循环期间数组是否在更改,因此它不会每次都重新评估array.length?

Can the statement be optimized so that the JVM knows whether the array is changing for the duration of the loop so that it does not reevaluate array.length every time?

推荐答案

如果另一个线程没有同时修改数组,则array.length将仅被有效评估一次,

if another thread is not modifying the array concurrently, will array.length be effectively evaluated only once,

更关键的是,除非该字段为volatile,否则JVM都会做出此假设,不管它是否正确.

More critically, unless the field is volatile the JVM will make this assumption whether it is true or not.

这篇关于Java优化器和冗余阵列评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆