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

标签 java bytecode javap

考虑非常简单的人为示例代码:

 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       
  1. 为什么编译器为非常相似的字段 ab 生成不同的字节码。两者都是用常量文字初始化的整数类型。

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

最佳答案

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 的更多信息&& JVMS

关于java - 为什么 javac 会为两个看似非常相似的结构生成不同的字节码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25167974/

相关文章:

java - java支持多重调度吗?如果不是,下面的代码如何工作?

java - JDK类方法的时间复杂度度量

java - 用 javap 反汇编的枚举不显示构造函数参数

java - 当注释存在时,ObjectMapper 忽略配置

java - Spring4 MVC Controller 可分页不起作用

ruby - 编译阻止了什么?

java - 使用 Java var 关键字的缺点

java - 什么是堆栈图框

Java 和 Javac : How to Determine Which Object Receives Invokevirtual

java - 在android数据库中存储 float