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());
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());
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.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.
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