I would like to know what is the difference between the two code snippet when I create a new object regarding efficiency, and memory use.
private Node head;
private int size;
public MyLinkedList(){
head = new Node(0,null);
size = 0;
}
vs.
private Node head= new Node(0,null);
private int size = 0;
public MyLinkedList(){
}
When your object is compiled, the compiler creates an instance initialization method for your constructors, e.g. for your class MyLinkedList, the compiler will for both versions of your class create the method as follows:
public void <init>(MyLinkedList this) {...}
This method is invoked when you use the new keyword or the MyLinkedList.class.newInstance() method.
Further, there are three ways to initialize your Object:
Instance Initialization:
private Node head;
private int size;
{
Node = new Node(0,null);
int = 0;
}
public MyLinkedList(){
}
The compiler will place instance variable initialization code, instance initialization code and the constructor body code in the <init> method. When you create a new instance, the first thing that the compiler will do is to allocate memory for the Object and all its instance variables by initializing the instance variables to their default values. Thereafter the <init> method is called. The exact sequence is outlined in the Java Language Specification:
That would mean that there is no difference regarding efficiency and memory use and the consideration of which one to use comes down to your use case and structuring, e.g. with multiple constructors you might have to duplicate the initialization code or make sure to call other constructors, with instance initialization you can catch exceptions or do more intricate calculations that you could not otherwise do with instance variable initialization.
To verify, you could install the Eclipse plugin Bytecode Outline and see that the resulting bytecode instructions and their order for the two versions of your class are practically the same:

On calling the constructor,
In case 1: both variables are initialized only if the overridden default constructor is called
In case 2: calling any other constructor will initialize the two variables. even though any initializations are not provided in those constructors.
So, if you have one and only one constructor which is this default constructor, then they behave the same. However the behavior varies if you have other constructors.
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