有哪些 Java 内存管理最佳实践? [英] What are some Java memory management best practices?

查看:28
本文介绍了有哪些 Java 内存管理最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从以前的开发人员那里接手了一些应用程序.当我通过 Eclipse 运行应用程序时,我看到内存使用量和堆大小增加了很多.经过进一步调查,我发现他们在循环中一遍又一遍地创建一个对象以及其他东西.

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);
    ...
}

对比

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.

另外,在上面的第二个循环之后,我将something"设置回 null 怎么样?这会清除一些记忆吗?

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?

更新:

到目前为止,我感谢大家的反馈.但是,我并没有真正询问上述循环(尽管根据您的建议,我确实回到了第一个循环).我正在尝试获得一些我可以留意的最佳实践.关于使用完集合后,将其清除"之类的内容.我真的需要确保这些应用程序不会占用太多内存.

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.

推荐答案

不要试图超越 VM.第一个循环是建议的最佳实践,无论是性能还是可维护性.在循环之后将引用设置回 null 将不能保证立即释放内存.当您使用尽可能小的范围时,GC 将发挥最佳作用.

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.

详细介绍这些内容(从用户的角度)的书籍是 Effective Java 2实施模式.

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

如果您想了解有关性能和 VM 内部的更多信息,您需要从 Brian 看讲座或阅读书籍戈茨.

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.

这篇关于有哪些 Java 内存管理最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆