为什么HotSpot会使用吊装优化以下内容? [英] Why HotSpot will optimize the following using hoisting?

查看:88
本文介绍了为什么HotSpot会使用吊装优化以下内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Effective Java中,作者提到

In the "Effective Java", the author mentioned that

while (!done) i++;

可以通过HotSpot优化到

can be optimized by HotSpot into

if (!done) {
    while (true) i++;
}



我对它非常困惑。变量 done 通常不是 const ,为什么编译器可以这样优化?


I am very confused about it. The variable done is usually not a const, why can compiler optimize that way?

推荐答案

作者认为变量 done 是一个局部变量,它在Java内存模型中没有任何要求要公开它没有同步原语的其他线程的值。或者换句话说: done 的价值不会被除此处所示之外的任何代码更改或查看。

The author assumes there that the variable done is a local variable, which does not have any requirements in the Java Memory Model to expose its value to other threads without synchronization primitives. Or said another way: the value of done won't be changed or viewed by any code other than what's shown here.

在这种情况下,由于循环不会改变 done 的值,因此可以有效地忽略其值,并且编译器可以将该变量的评估提升到外部循环,防止它在循环的热部分进行评估。这使循环运行得更快,因为它必须做更少的工作。

In that case, since the loop doesn't change the value of done, its value can be effectively ignored, and the compiler can hoist the evaluation of that variable outside the loop, preventing it from being evaluated in the "hot" part of the loop. This makes the loop run faster because it has to do less work.

这也适用于更复杂的表达式,例如数组的长度:

This works in more complicated expressions too, such as the length of an array:

int[] array = new int[10000];
for (int i = 0; i < array.length; ++i) {
    array[i] = Random.nextInt();
}

在这种情况下,天真的实现将评估数组的长度10,000次,但由于永远不会分配变量数组,并且数组的长度永远不会改变,因此评估可以更改为:

In this case, the naive implementation would evaluate the length of the array 10,000 times, but since the variable array is never assigned and the length of the array will never change, the evaluation can change to:

int[] array = new int[10000];
for (int i = 0, $l = array.length; i < $l; ++i) {
    array[i] = Random.nextInt();
}

此处的其他优化也适用于与吊装无关。

Other optimizations also apply here unrelated to hoisting.

希望有所帮助。

这篇关于为什么HotSpot会使用吊装优化以下内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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