Ravi Jain
Ravi Jain

Reputation: 1482

Resource Handling Practice

It's assured that Garbage Collector destroys all the unwanted and unused objects, what if we manually nullify the objects eg. List<String> = null , does this action makes any negative or positive performance effect?

I am on Java. Thanks.

Upvotes: 0

Views: 165

Answers (3)

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

Explicit nulling makes little or no difference. Usually the GC can reliably detect when an object can no longer be reached, and can thus be GCd.

Particularly, nulling stack (i.e. inside methods) variables helps absolutely nothing. It's trivial to for the runtime to automatically detect when they will be needed and when not. nulling heap (i.e. inside classes) variables could in some rare instances help, but that's a rare exception, and probably does more harm (in code legibility/maintainability) than good.

Also note that nulling doesn't guarantee if, or when, an object will be GCd.

Upvotes: 1

Hardik Mishra
Hardik Mishra

Reputation: 14877

Garbage collection is a way in which Java recollects the space occupied by loitering objects. By doing so, it [Java] ensures that your application never runs out of memory (though we cannot be assured that the program will ever run out of memory).

It is suggested to leave it on JVM.

Read related : Does setting Java objects to null do anything anymore?

Upvotes: 1

posdef
posdef

Reputation: 6532

Not an expert on details of memory handling but I can share what I know. GC will collect whatever is not used. Thus when you eliminate the last reference to an object (by explicitly nullifying) you'll be marking it for garbage collection. This does not guarantee that it'll be collected immediately.

You can explicitly try and invoke GC but you'll see lots of people advising against it. My understanding is that the call to GC is unreliable at best. The whole point with GC and Java is that you as a programmer should not need to worry much about the memory allocation. As for performance, unless you have tight limitations for heap space, you shouldn't notice GC activity.

Upvotes: 1

Related Questions