-1

Which is more efficient or SAFE regarding memory and all ?

classA A = new classA();
classB B = new classB(A);
A.dispose();

or

classB B = new classB(new classA());
BenMorel
  • 34,448
  • 50
  • 182
  • 322
fahimalizain
  • 844
  • 8
  • 15
  • 1
    I think it's generally a fishy idea to have the caller call A.dispose() when A is "passed off to" the constructor of B, because the general reason to pass A to B's constructor is to store it for later use. Consider having B "own" A and "dispose" A as appropriate. Many of the [Java IO wrapper classes work this way](http://stackoverflow.com/questions/1388602/do-i-need-to-close-both-filereader-and-bufferedreader): most streams will automatically "close" (or "dispose") the underlying source. – user2864740 Apr 15 '14 at 05:36

3 Answers3

1

THERE IS NO DIFFERENCE.

Example :

Consider the following code.

class A {
}

class B {
    public B(A a) {

    }
}

class  Test
{
    public static void main (String[] args) 
    {
        A a = new A();
        B b1 = new B(a);

        B b2 = new B(new A());
    }
}

If you will see the compiled code below you will find that java compiler includes two invokespecial and two new instructions, so each time a separate Object of class A will be created and stored in heap, Reference of that object will be passed as parameter to constructor of class B.

Compiled code :

class Test extends java.lang.Object{
Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   new         #2; //class A                   
   3:   dup
   4:   invokespecial   #3; //Method A."<init>":()V     
   7:   astore_1
   8:   new         #4; //class B                   
   11:  dup
   12:  aload_1
   13:  invokespecial   #5; //Method B."<init>":(LA;)V  
   16:  astore_2
   17:  new         #4; //class B                  
   20:  dup
   21:  new         #2; //class A                  
   24:  dup
   25:  invokespecial   #3; //Method A."<init>":()V    
   28:  invokespecial   #5; //Method B."<init>":(LA;)V 
   31:  astore_3
   32:  return

}

You can see that just execution order is changed.

Side Note :

  • invokespecial JVM instruction is used to invoke constructor (Instance initialization method) of class.
  • new is used to create a new instance of class.
  • <init> is a special name of constructor supplied by compiler, and it is not a valid java identifier.
Not a bug
  • 4,286
  • 2
  • 40
  • 80
0

If you are never going to use ClassA A then there is no point in defining it. As for efficient or SAFE regarding memory and all - no difference.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
-1

Do not create ClassA A = new ClassA(); because you are not using it. unnecessarily you are giving work for heap. directly write classB B = new classB(new classA()); hope this will helps you

GvSharma
  • 2,632
  • 1
  • 24
  • 30