为什么Java字节码“存储”?经常跟随“负载”吗? [英] Why does java bytecode "store" often followed by "load"?

查看:55
本文介绍了为什么Java字节码“存储”?经常跟随“负载”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从一些小的Java函数中读取jvm字节码时,我发现当在操作数堆栈上计算一个新的局部变量时,假设它将存储在局部变量表中,但通常会将其加载到立即操作数堆栈(就字面意义而言,就字节码而言)。我对操作不太了解,是不必要的操作吗?

When I read jvm bytecode which from some small java function, I found that when a new local variable is caculated on the operand stack, assuming that it will be stored in the local variable table, but usually it will be loaded to the operand stack immediately (just in the terms of bytecode literally). I don't understand the operation well, is it unnecessary operation?

推荐答案

Java编译器倾向于以非常简单的方式进行编译

The Java compiler tends to compile things in a very simple and straightforward manner, leaving optimization to the JIT.

例如,如果您写 x * = 3; x * = 4; ,您大概会得到字节码

For example, if you write x *= 3; x *= 4;, you'll probably get bytecode along the lines of

iload_1
iconst_3
imul
istore_1
iload_1
iconst_4
imul
istore_1

理论上,编译器可以确定存储/装入对是多余的,可以将其删除。但是有几个理由不这样做-1)这增加了很多复杂性,却无济于事,因为JIT无论如何都会对所有内容进行优化2)它使调试更加困难,因为您不再可以访问所有局部变量的值3)如果在此表达式的中间抛出异常,则局部变量将具有错误的值。

The compiler could theoretically figure out that the store/load pair is redundant and remove it. But there are several reasons to not do so - 1) this adds a lot of complexity for no benefit as the JIT optimizes everything anyway 2) it makes debugging harder, since you no longer have access to the values of all the local variables 3) if an exception is somehow thrown in the middle of this expression, the local variables will have the incorrect values.

这篇关于为什么Java字节码“存储”?经常跟随“负载”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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