With regard to Memory usage and variable instantiation which is better or is there no difference :
This
for(int i = 0; i < someValue; i++)
{
Obj foo = new Obj();
Use foo.....
}
As opposed to:
Obj foo;
for(int i = 0; i < someValue; i++)
{
foo = new Obj();
Use foo.....
}
There is no difference. Any potential difference in terms of memory usage would be optimized by the compiler.
If you compile (using javap -c
) the two examples and compare the bytecode, you'll find that the bytecode is the same. Of course, this depends on the JVM version. But since this example is so trivial, it's probably safe to assume that neither is more memory efficient than the other.
Code:
public class example1 {
public static void main(String[] args) {
for (int i=0; i<10; i++) {
Object a = new Object();
}
}
}
Bytecode:
public class example1 extends java.lang.Object{
public example1();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: bipush 10
5: if_icmpge 22
8: new #2; //class java/lang/Object
11: dup
12: invokespecial #1; //Method java/lang/Object."<init>":()V
15: astore_2
16: iinc 1, 1
19: goto 2
22: return
}
Code:
public class example2 {
public static void main(String[] args) {
Object a;
for (int i=0; i<10; i++) {
a = new Object();
}
}
}
Bytecode:
public class example2 extends java.lang.Object{
public example2();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_2
2: iload_2
3: bipush 10
5: if_icmpge 22
8: new #2; //class java/lang/Object
11: dup
12: invokespecial #1; //Method java/lang/Object."<init>":()V
15: astore_1
16: iinc 2, 1
19: goto 2
22: return
}
With modern JVM both will work the same, also compiler optimization will take make both of them same.
Ignoring compiler optimization and modern JVM, 1st approach is better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With