有一种普遍的做法如何使垃圾收集器释放内存在.NET更容易? [英] Is there a common practice how to make freeing memory for Garbage Collector easier in .NET?

查看:125
本文介绍了有一种普遍的做法如何使垃圾收集器释放内存在.NET更容易?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想,如果有一种方法如何加快.NET释放内存。我创建一个游戏在.NET中(只有管理code)如不需要任何显著的图形,但我仍想以不失去对性能没有正确写出来。

例如它是有用的分配空值对象不是不再需要?我看到这几样在互联网。

解决方案
  

时是很有用的空值分配给那些不再需要的对象呢?

一般情况下,没有。大部分样品,你会看到网上说这样做是通过人们来自VB6,在那里,这是一个常见的​​最佳做法.NET。在.NET中,它是没有多大帮助。如果你有一个很长的运行方式,它可以让垃圾收集器找对象早一点—但如果你的方法是很长,你有其他问题。

相反,在.net中你应该建立短期方法,并在最小的范围内尽可能阻止尽可能晚地定义你的变量。使用变量的自然寿命由范围决定的,但要保持自然寿命短。

您应该的没有的做你自己的垃圾收集,通过至少一种其他的答案在这里的建议。这实际上可以使事情的的。 .NET使用代垃圾收集器。通过强制垃圾收集,您的也许的收集目标对象(也可能不会 - 也不能保证垃圾回收)。但你也有可能迫使一堆无法收集尚未被存储在一个较高的订单产生其他对象,使他们难以收集的未来。因此,只要不这样做。

I've been thinking if there's a way how to speed up freeing memory in .NET. I'm creating a game in .NET (only managed code) where no significant graphics is needed but still I would like to write it properly in order to not to lose performance for nothing.

For example is it useful to assign null value to objects that are not longer needed? I see this in a few samples over Internet.

解决方案

is it useful to assign null value to objects that are not longer needed?

Generally, no. Most of the samples you'll see online that do this are by people that came to .Net from VB6, where this was a common best practice. In .Net, it's less helpful. If you have a very long running method, it might let the garbage collector find the object a little earlier — but if your method is that long you have other problems.

Instead, in .Net you should build short methods and define your variables as late as possible in the smallest scope blocks possible. Use the "natural" lifetime of the variable as determined by scope, but keep that natural lifetime short.

You should not be doing your own garbage collection, as suggested by at least one other answer here. This can actually make things slower. .Net uses a generational garbage collector. By forcing a garbage collection, you might collect the target object (you also might not - there are no guarantees with garbage collection). But you'll likely also force a bunch of other objects that you can't collect yet to be stored in a higher order generation, making them harder to collect in the future. So just don't do this.

这篇关于有一种普遍的做法如何使垃圾收集器释放内存在.NET更容易?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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