在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
根本不这样做。