Reputation: 4079
I can't find anything that is a direct answer to this question but if I am mistaken please link the right question.
Essentially, I'm asking whether there are any disadvantages of this:
MyObject myObject = new MyObject();
this.classReference = myObject;
as compared to this:
this.classReference = new MyObject();
My guess is that differences would be negligible after the code is compiled to bytecode.
Upvotes: 1
Views: 65
Reputation: 1441
In this:
MyObject myObject = new MyObject();
this.classReference = myObject;
you have two variables holding a reference to one object. It is important to understand that 'myObject' is not 'an object', it holds a reference to an object. 'new' returns a reference, the reference is stored in `myObject', and copied to 'classReference'.
(By the way, your variable seems misnamed -- it is not a reference to a class, it is a reference to an object, an instance of a class.)
So the only difference between the above and this:
this.classReference = new MyObject();
is that in the former case, there was space allocated on the stack for a local variable (but the allocation was probably in the method prologue, so takes no extra time), and then you need to copy the reference somewhere else. The extra overhead is very very small.
This is assuming that the compiler doesn't optimize away 'myObject' in the first place.
Upvotes: 3