Reputation: 111
Does the first example produce more efficient code than the second in Java/Android and in generally in Java?
At least the first example can not be slower than second, I think..
I do not care here that the variable v may live longer time in first example, perhaps eating memory for a longer time.
Of course it is true that second way of doing is more readable if you have more complicated code with several inner blocks. Also that is not the issue here.
MyType v;
for(int i=0;i<bigCount;++i)
{
v = <value produced for i>;
//do something with v
}
for(int i=0;i<bigCount;++i)
{
MyType v = <value produced for i>;
//do something with v
}
Upvotes: 2
Views: 113
Reputation: 37813
I've created a minimal example:
public void option1() {
String s;
for (int i = 0; i < foo; i++) {
s = String.valueOf(i);
}
}
public void option2() {
for (int i = 0; i < foo; i++) {
String s = String.valueOf(i);
}
}
And found that the generated bytecode is identical for both:
option1()
:
0 iconst_0
1 istore_2
2 goto 13 (+11)
5 iload_2
6 invokestatic #17 <java/lang/String/valueOf(I)Ljava/lang/String;>
9 astore_1
10 iinc 2 by 1
13 iload_2
14 aload_0
15 getfield #23 <MethodTest/foo I>
18 if_icmplt 5 (-13)
21 return
option2()
:
0 iconst_0
1 istore_1
2 goto 13 (+11)
5 iload_1
6 invokestatic #17 <java/lang/String/valueOf(I)Ljava/lang/String;>
9 astore_2
10 iinc 1 by 1
13 iload_1
14 aload_0
15 getfield #23 <MethodTest/foo I>
18 if_icmplt 5 (-13)
21 return
My guess is, if the compiler sees, that the variable created before the loop is never used after the loop, it just pulls it's definition into the loop. So in your case, neither is more efficient. So go with the one that's more readable (option2()
).
Upvotes: 1
Reputation: 2173
to prevent multiple allocations, you can close the variable in it's own scope like this:
{
MyType v;
for(int i=0;i<bigCount;++i)
{
v = <value produced for i>;
//do something with v
}
}
v
will be collected by the GC
after this block
Upvotes: 0
Reputation: 32391
I would choose the second option because the v
variable scope is inside the for
loop. It doesn't need to be used anywhere outside.
This way, the objects that are created and assigned to v
are eligible for garbage collection earlier. Or at least the last one will be eligible faster than in the first piece of code.
Upvotes: 2