加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

为什么javac为两个看似非常相似的结构生成不同的字节代码?

发布时间:2020-12-15 04:21:41 所属栏目:Java 来源:网络整理
导读:考虑一下非常简单的人为设计代码: public class TestJavap { public static void main(String[] args) { int a = 3; int b = 7; }} javap产生这个: public static void main(java.lang.String[]); Code: 0: iconst_3 1: istore_1 2: bipush 7 4: istore_2
考虑一下非常简单的人为设计代码:

public class TestJavap {
    public static void main(String[] args) {
        int a = 3;
        int b = 7;
    }
}

javap产生这个:

public static void main(java.lang.String[]);
  Code:
   0: iconst_3      
   1: istore_1      
   2: bipush        7
   4: istore_2      
   5: return

>为什么编译器为非常相似的字段a和b生成不同的字节代码.两者都是用常量文字初始化的整数类型.

对于它,它通过iconst_3从池中获取常量,然后通过istore_1将其存储在变量中,而对于b,它使用完全不同的机制(bipush和istore的组合).

解决方法

why the compiler is producing different byte code for very similar fields a and b

从整数-1-5中使用iconst_x(x是0-5的数字),它已经是一个常数字节码.

iconst_m1   02      → -1    load the int value -1 onto the stack
iconst_0    03      → 0 load the int value 0 onto the stack
iconst_1    04      → 1 load the int value 1 onto the stack
iconst_2    05      → 2 load the int value 2 onto the stack
iconst_3    06      → 3 load the int value 3 onto the stack
iconst_4    07      → 4 load the int value 4 onto the stack
iconst_5    08      → 5 load the int value 5 onto the stack

因此,如果该数字不是iconst_字节码的常量值,那么它将使用bipush字节码.

有关list of java bytecode&&amp ;;的更多信息JVMS

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读