.netwpfgarbage-collectionmanaged-code

Is there a common practice how to make freeing memory for Garbage Collector easier in .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.


Solution

  • 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.