JVM字节码输出

Raj*_*ena 2 java jvm

在JVM规范中,以下示例

void createThreadArray() {
    Thread threads[];
    int count = 10;
    threads = new Thread[count];
    threads[0] = new Thread();
}
Run Code Online (Sandbox Code Playgroud)

产生

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
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么我们一开始istore_2iload_2采用这种方法呢?我们难道不能只使用bipush 10堆栈中的值来创建新的对象数组吗?这背后的设计考虑是什么?

wer*_*ero 5

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

通过使用直译,很容易构造字节码编译器.任何优化分析都很难,并且已经在运行时中实现,因此javac根本不会这样做.