What are JAVA memory management best practices?

I'm taking over some applications from former developers When I run the application through eclipse, I see a lot of increase in memory usage and heap size After further investigation, I found that they were creating an object and other things in the loop

I started going through some cleaning up But the more I experience, the more I want to ask, "what will this actually do?"

For example, instead of declaring a variable outside the loop mentioned above, they just set its value in the loop... They create an object in the loop Well, I mean:

for(int i=0; i < arrayOfStuff.size(); i++) {
    String something = (String) arrayOfStuff.get(i);
    ...
}

And

String something = null;
for(int i=0; i < arrayOfStuff.size(); i++) {
    something = (String) arrayOfStuff.get(i);
}

I'm not right. Is the bottom loop better? Maybe I was wrong

Also, after the second loop above, I set "something" to null? Will this erase some memories?

In either case, what good memory management best practices can I follow that will help keep memory usage low in my application?

to update:

So far, I thank everyone for their feedback However, I didn't really ask about the above cycle (although I did go back to the first cycle according to your suggestion) I'm trying to get some best practices I can pay attention to When you finish using the collection, clear it I really need to make sure these applications don't take up too much memory

Solution

Don't try to surpass VM The first cycle is recommended best practices, including performance and maintainability Setting the reference back to null after a loop does not guarantee immediate memory release GC works best when you use a minimum range

Books detailing these contents (from the user's point of view) are effective Java 2 and implementation patterns

If you want to know more about performance and VM internals, you need to check the talks or read the books in Brian Goetz

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>