Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is it good to set null to all variables?

Status
Not open for further replies.

dennismichel

Programmer
Jul 23, 2003
7
BR
Hi
I have a jsp based application.
I'd like to know if it's good practice to set all variables to null, after using. I read that it helps the garbage collector to determine unused variables.
I have several variables such as String, arrays, vectors and arraylists.
I set to null only the vectors and arraylists.
Do you think, is it good to do it for String and array variables?
Thank's dennis michel.
 
I don't think it could hurt your application any and it would probably help especially if you explicitly call the garbage collector.
 
One other idea though is that if unless your application is running on a low end server or happens to be quite large, I don't think you need to worry about the basics like Strings. Arrays would be useful if they are very large, else I doubt it will help significantly.
 
When I declared a variable in a jsp file and I was redirected to another page, the variable lost the reference?
I have an Vector of String Arrays and set null to it.
In this case the arrays will be collected by gc?
Thank's dennis michel.

 
The variable probably only had local scope, hence being lost, and if you set null to the Vector then yes, it should be collected if there are no other references(variables) pointing to it anymore.
 
I have other question.
In my jsp files I use the session object to store variables.
When I set to null the session or other value, the variable stored lost the reference? And the variable is able to be collected by gc?
Thank's dennis michel
 
Setting variables to null after use MIGHT help with garbage collection, but mostly it helps to prevent initialisation errors. If you set them to null those become immediately visible through NullPointerExceptions, if you don't you'll continue with the old data which might mask errors for a while or make you look in the wrong place for them.
 
Hi,This is how to look at it.If you set the variables to null,then when the Garbage collector comes it will definately collect.However you cannot predict when the collector will run.Its even worse in a jsp ,the behavior of the collector becomes even more unpredictable.This should not be a problem however as servelet engine will force collection when needed.
All said ,its good practice to set them to null.If you make this a habit ,then you will at least gurantee that your variables are always ready for the collector (whenever it comes along.Not to mention the performance advantages .
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top