Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Efficiency in Java

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.....
}
like image 376
Aiden Strydom Avatar asked Nov 28 '22 07:11

Aiden Strydom


2 Answers

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.


Example 1:

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
}

Example 2:

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
}
like image 136
Alex Lockwood Avatar answered Dec 04 '22 21:12

Alex Lockwood


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.

like image 39
mprabhat Avatar answered Dec 04 '22 21:12

mprabhat