3

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

 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 它使用完全不同的机制(bipush和 的组合istore)。

4

1 回答 1

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列表的更多信息

于 2014-08-06T18:59:38.017 回答