What are some Java memory management best practices? [closed]

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.


Don't try to outsmart the VM. The first loop is the suggested best practice, both for performance and maintainability. Setting the reference back to null after the loop will not guarantee immediate memory release. The GC will do its job best when you use the minimum scope possible.

Books which cover these things in detail (from the user's perspective) are Effective Java 2 and Implementation Patterns.

If you care to find out more about performance and the inners of the VM you need to see talks or read books from Brian Goetz.


Those two loops are equivalent except for the scope of something; see this question for details.

General best practices? Umm, let's see: don't store large amounts of data in static variables unless you have a good reason. Remove large objects from collections when you're done with them. And oh yes, "Measure, don't guess." Use a profiler to see where the memory is being allocated.


There are no objects created in both of your code samples. You merely set an object reference to a string that is already in the arrayOfStuff. So memorywise there is no difference.