What are some Java memory management best practices?
- by Ascalonian
I am taking over some applications from a previous developer. When I run the applications through Eclipse, I see the memory usage and the heap size increase a lot. Upon further investigation, I see that they were creating an object over-and-over in a loop as well as other things.
I started to go through and do some clean up. But the more I went through, the more questions I had like "will this actually do anything?"
For example, instead of declaring a variable outside the loop mentioned above and just setting its value in the loop... they created the object in the loop. What I mean is:
for(int i=0; i < arrayOfStuff.size(); i++) {
String something = (String) arrayOfStuff.get(i);
...
}
versus
String something = null;
for(int i=0; i < arrayOfStuff.size(); i++) {
something = (String) arrayOfStuff.get(i);
}
Am I incorrect to say that the bottom loop is better? Perhaps I am wrong.
Also, what about after the second loop above, I set "something" back to null? Would that clear out some memory?
In either case, what are some good memory management best practices I could follow that will help keep my memory usage low in my applications?
Update:
I appreciate everyones feedback so far. However, I was not really asking about the above loops (although by your advice I did go back to the first loop). I am trying to get some best practices that I can keep an eye out for. Something on the lines of "when you are done using a Collection, clear it out". I just really need to make sure not as much memory is being taken up by these applications.