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

 看电影天堂4 发布于 2022-12-29 17:35

考虑一下非常简单的人为设计代码:

 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       

    为什么编译器非常类似领域生产不同字节码ab.两者都是用常量文字初始化的整数类型.

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

Rod_Algonqui.. 7

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字节码.

有关java字节码 && JVMS 列表的更多信息

1 个回答
  • 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字节码.

    有关java字节码 && JVMS 列表的更多信息

    2022-12-29 17:38 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有