我写了2个方法test1和test2,并添加了编译字节码的主要部分(Snow Leopard上的Java 1.6)作为注释:
/*
* 14 iload_1 [b] -> load value from address 1 to sack
* 15 iastore -> store value from stack into int array
* 16 iinc 3 1 [i] -> int increment value of address 3
* 19 iinc 3 1 [i] -> int increment value of address 3
*/
public void test1() {
int b = 0;
int a[] = new int[10];
for (int i=0; i<10; i++) {
a[i] = b;
i++;
}
}
/*
* 14 iinc 3 1 [i] -> increment value of address 3
* 17 iload_1 [b] -> load value from address 1 to stack
* 18 iastore -> store value from stack into int array
* 19 iinc 3 1 [i] -> increment value of address 3
*/
public void test2() {
int b = 0;
int a[] = new int[10];
for (int i=0; i<10; i++) {
a[i++] = b;
}
}
操作的顺序是不同的。但是两种方法 test1 和 test2 的运算和是相等的!因此,字节码的性能也应该相同。inc