2

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
}
4

3 に答える 3

2

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.

于 2013-02-23T13:14:23.700 に答える
1

最小限の例を作成しました:

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);
    }
}

そして、生成されたバイトコードは両方で同一であることがわかりました:

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

私の推測では、ループの前に作成された変数がループの後に使用されることはなく、コンパイラはその定義をループにプルするだけです。したがって、あなたの場合、どちらもより効率的ではありません。したがって、より読みやすいものを使用してください(option2())。

于 2013-02-23T13:40:08.850 に答える
0

複数の割り当てを防ぐために、次のように独自のスコープで変数を閉じることができます。

{
  MyType v;
  for(int i=0;i<bigCount;++i)
  {
    v = <value produced for i>;
    //do something with v
  }
}

vGCこのブロックの後によって収集されます

于 2013-02-23T13:21:53.260 に答える