• Post Reply Bookmark Topic Watch Topic
  • New Topic

explicitly declaring 'null' & gc  RSS feed

 
Allen Bandela
Ranch Hand
Posts: 128
Eclipse IDE MS IE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would explicitly making a variable 'null', after it is being used, help the garbage collector? I mean, will it save the 'gc' time for determining if the object has no more references and needs to be gc'd. Will this have an effect on performance.

thanks
[ October 17, 2007: Message edited by: Sylvester James ]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While any object references point to an object, it cannot be garbage-collected.

If you have an object field or method-local variable that refers to a particular object, but you know that this reference is no longer needed, then setting it to null may allow the object to be GCd earlier. That will free up memory, which may improve your application's performance.

It is, in practice, often not worth doing so. Most method-local variables go out of scope quite quickly, and this removes the reference. Most objects are not very big, and not worth worrying too much about.

In contrast, splashing statements setting things to null all over your source code will make it difficult to read and to maintain, and wastes memory in a different way.

Try to be intelligent about this. If there might be loads of these references held for a long time (e.g. in a long-lived Collection), set them to null. If it's just a few references for a short time, forget it, and keep your code simple.

Something that is often more worthwhile is ensuring that your variables have the smallest scope that fulfils the requirement. Then the scope will automatically deal with removing the reference, without any need for messy explicit nulling.

Premature optimisation is a certified Bad Thing.
[ October 17, 2007: Message edited by: Peter Chase ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!