JVM字节码输出

JVM byte code output

在 JVM 规范中,以下示例

void createThreadArray() {
    Thread threads[];
    int count = 10;
    threads = new Thread[count];
    threads[0] = new Thread();
}

生产

Method void createThreadArray()
0   bipush 10           // Push int constant 10
2   istore_2            // Initialize count to that
3   iload_2             // Push count, used by anewarray
4   anewarray class #1  // Create new array of class Thread
7   astore_1            // Store new array in threads
8   aload_1             // Push value of threads
9   iconst_0            // Push int constant 0
10  new #1              // Create instance of class Thread
13  dup                 // Make duplicate reference...
14  invokespecial #5    // ...for Thread's constructor
                        // Method java.lang.Thread.<init>()V
17  aastore             // Store new Thread in array at 0
18  return

我的问题是,为什么我们在开始时在这个方法中先做 istore_2 然后 iload_2?我们不能只使用 bipush 10 压入堆栈的值来创建新的对象数组吗?这背后的设计考虑是什么?

javac 不是优化编译器。当运行时检测到它是热点时,在 JVM 运行时进行优化,如删除不必要的局部变量 count

通过直译,很容易构造出字节码编译器。任何优化分析都很难,并且已经在运行时实现了,所以javac干脆不做。

如前所述,Javac 并未优化此模式。
但是,不是因为不能,而是不能这样。

对于源代码中的每个局部变量,Javac 在 class 文件 (JVMS §2.6.1). The liveness range of this variable along with its local variable index is stored in LocalVariableTable attribute (JVMS §4.7.13).

的局部变量数组中保留一个槽

此信息对于调试是必需的。局部变量数组提供了从源代码中的变量到字节码中的变量的映射。例如。您可以在您的代码中的第

行设置一个断点
threads = new Thread[count];

并查询字节码中映射到locals[2]count变量的值。