想象一下那些版本的函数:
static int fibonacciIterative(int n) {
int previous = 0;
int current = 1;
for (int i = 1; i < n; i++) {
int temp = current;
current += previous;
previous = temp;
}
return current;
}
static int fibonacciIterative(int n) {
int previous = 0;
int current = 1;
int temp;
for (int i = 1; i < n; i++) {
temp = current;
current += previous;
previous = temp;
}
return current;
}
唯一的区别是,变量temp
在第一个版本的循环中声明为[[再次],而在第二个版本的循环外部则声明为[[once。无论重要性如何,生成的字节码是否有差异?编译器如何处理这种情况,第二版本可以视为optimized第一版本吗?
temp
和i
以不同的顺序分配了插槽,但是字节码在其他方面是相同的。 话虽这么说,这比您想象的还要无关紧要,因为字节码不是(大多数时候)JVM所执行的。相反,它仅仅是一个抽象。对于性能实际上很重要的任何代码,JVM都会对您的代码进行静态分析,然后对其进行优化并将其编译为本机代码,因此字节码编码中的琐碎差异还是完全没有意义的。