E
Ed Thompson
I have long had the question of whether is is better to declare a
vraible inside a loop or outside a loop in Java.
To test I wrote the following code:
public class LoopTest {
public void inside() {
for(int i=0; i< 10;i++)
{
String x = "Edward";
}
}
public void outside() {
String x = null;
for(int i=0; i< 10;i++)
{
x = "Edward";
}
}
}
Which I disassembled using javap -c:
public void inside();
Code:
0: iconst_0
1: istore_1
2: iload_1
3: bipush 10
5: if_icmpge 17
8: ldc #2; //String Edward
10: astore_2
11: iinc 1, 1
14: goto 2
17: return
public void outside();
Code:
0: aconst_null
1: astore_1
2: iconst_0
3: istore_2
4: iload_2
5: bipush 10
7: if_icmpge 19
10: ldc #2; //String Edward
12: astore_1
13: iinc 2, 1
16: goto 4
19: return
If I read this right, it indicates that 'redelcaring' the variable
inside the loop is 2 opcodes shorter The first two opcodes in outside()
are not in inside()).
So now I have an interpretation issue. Does this really mean that
inside() is faster than outside()? Is one really more optimal?
Can someone help explain what is happening? (Not the line by line, but
what is java really doing?)
Thanx
vraible inside a loop or outside a loop in Java.
To test I wrote the following code:
public class LoopTest {
public void inside() {
for(int i=0; i< 10;i++)
{
String x = "Edward";
}
}
public void outside() {
String x = null;
for(int i=0; i< 10;i++)
{
x = "Edward";
}
}
}
Which I disassembled using javap -c:
public void inside();
Code:
0: iconst_0
1: istore_1
2: iload_1
3: bipush 10
5: if_icmpge 17
8: ldc #2; //String Edward
10: astore_2
11: iinc 1, 1
14: goto 2
17: return
public void outside();
Code:
0: aconst_null
1: astore_1
2: iconst_0
3: istore_2
4: iload_2
5: bipush 10
7: if_icmpge 19
10: ldc #2; //String Edward
12: astore_1
13: iinc 2, 1
16: goto 4
19: return
If I read this right, it indicates that 'redelcaring' the variable
inside the loop is 2 opcodes shorter The first two opcodes in outside()
are not in inside()).
So now I have an interpretation issue. Does this really mean that
inside() is faster than outside()? Is one really more optimal?
Can someone help explain what is happening? (Not the line by line, but
what is java really doing?)
Thanx