コード部分の両方のバイトコードを比較しました。特別なことは何も見つかりませんでした。唯一の違いは、最初のサンプルコード部分では4つのローカル変数が定義されていますが、2番目のサンプルコード部分では5つのローカル変数が定義されていることです。ただし、同様のオペコードが実行されます。ローカル変数名は異なるため、オペコードが実行されます。つまり、最初の例では「iはlocal-variable-2」として定義され、2番目の例では「iはlocal-variable-4」として定義されています。
ただし、JVMツールを介してコードの実行を監視すると、追加情報が得られる場合があります。Javaはプラットフォームであり、JVMはコードの実行を最適化する可能性があるため、JavaソースコードまたはJavaバイトコードのいずれかを調べてもわからない場合があります。
Object[] objs = new Object[5];
for (int i = 0; i < 5; ++i) {
int j = i + 1;
Object obj = objs[i];
}
local-variable-0=this
local-variable-1=objs
local-variable-2=i
local-variable-3=j
stack=2, locals=5, args_size=1
0: aload_0
1: invokespecial #8 // Method java/lang/Object."<init>":()V
4: iconst_5
5: anewarray #3 // class java/lang/Object
8: astore_1 #store created object referance to local value-1 (objs)
9: iconst_0 #push 0 on stack
10: istore_2 # local-value-2(i) assigned 0
11: goto 26
14: iload_2 #load localvalue 2(i)
15: iconst_1 # ++i operation
16: iadd #i+1
17: istore_3 #assign i+1 into local-variable-3(j)
18: aload_1 # push object in local varable 1 (objs) onto the stack
19: iload_2 # push integer in local variable 2 (i) onto the stack
20: aaload # retrieve entry
21: astore 4 # push value on stack into local-variable-4 (obj)
23: iinc 2, 1 # local-variable-2(i)++
26: iload_2
27: iconst_5
28: if_icmplt 14 for(if i==5)
31: return
**************************************************************************
Object[] objs = new Object[5];
int j;
Object obj;
for (int i = 0; i < 5; ++i) {
j = i + 1;
obj = objs[i];
}
local-variable-0=this
local-variable-1=objs
local-variable-2=j
local-variable-3=obj
local-variable-4=i
stack=2, locals=5, args_size=1
0: aload_0
1: invokespecial #8 // Method java/lang/Object."<init>":()V
4: iconst_5
5: anewarray #3 // class java/lang/Object
8: astore_1 #store created object referance to local value-1 (objs)
9: iconst_0 #push zero on to the stack
10: istore 4 # local variable-4(i) is assigned zero
12: goto 28
15: iload 4
17: iconst_1
18: iadd #i+1
19: istore_2 #j is set
20: aload_1 #load objs
21: iload 4 #load i
23: aaload
24: astore_3 #obj=objs[i]
25: iinc 4, 1 # i++
28: iload 4
30: iconst_5
31: if_icmplt 15 # if i==5
34: return