Reputation: 35054
public void function(){
new Student().setName("john");
}
public void function(){
Student student = new Student();
student.setName("john");
}
Does GC behave differently for both of the snip?
I mean which case (CASE-1/CASE-2) is more GC efficient in terms of Time?
Upvotes: 0
Views: 756
Reputation: 99
Answer for question is no.
Gc behaves nearly same for both cases.
Garbage Collector has a unpredictable behavior. But Any Object which is no longer referred or is no longer in use is eligible for garbage collection.
Case 1 : Main objective of anonymous object is for instant use (one time use). So after line "new Student().setName("john");" , your anonymous object is not in use so it will be GC.
case 2 : Student student = new Student();
student.setName("john");
After this line student reference is no longer referred so it will be GC.
There are few chances that in case 2 student reference may be leaked but GC is smart enough to handle this.
Now in case 1 if you want object for one time use then go for anonymous object as Objects are created in heap memory and GC sweep heap memory. Stack memory are managed in such way that memory used by stack is reclaimed automatically.
You can referred this link for more.
Upvotes: 0
Reputation: 3219
In the first case you don't assign the newly created object to a variable, hence it becomes unreachable for the code (and thus becomes a candidate for garbage collection) as soon as setName (String name)
method returns.
In the second case local variable student
will prevent the student object from being garbage collected until it goes out of scope. In other words, in the second snippet the student object will continue to be a live object after setName(String name)
returns and will become a candidate for garbage collection only after the method function()
returns.
UPDATE:
In terms of the time required for garbage collection both cases are equal since in all of them you end up having one garbage object.
Upvotes: 2
Reputation: 279990
Does GC behave differently for both of the snip?
No. Once the setName
method has been invoked, the Student
object created with new Student
is no longer reachable and can be garbage collected.
I mean which case (CASE-1/CASE-2) is more GC efficient in terms of Time?
Neither is more efficient. The first case will have one less assignment in the bytecode. This does not affect GC whatsoever.
From the JLS
A reachable object is any object that can be accessed in any potential continuing computation from any live thread.
In both snippets, after the invocation of setName
, the Student
object is no longer reachable (assuming the constructor and the setName
method don't leak references to the object - but even in that case, the behavior of both snippets would be the same).
Upvotes: 4