Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and .Net Garbage collector performance

Tags:

I am trying to make a game in C# and .NET, and I was planning to implement messages that update the game objects in the game world. These messages would be C# reference objects.

I want this approach because doing it this way would be easier to send them over a network if I want the game to be multiplayer.

But if I have a lot of messages, won't it be quite stressful for the garbage collector? And won't that affect gameplay? The message classes themselves are quite small with 4 or 5 members at most.

These messages will be generated a couple of times per second for each object in the game world.

like image 438
Alecu Avatar asked Apr 26 '13 08:04

Alecu


2 Answers

In .NET the garbage collector has 3 generations, generation 0, generation 1 and generation 2. Every Time the GC fails to collect an object in a generation, that object will be promoted to the next generation.

You could potentially run into issues if your objects are larger than 85kb. These objects will be automatically stored in the large object heap. The large object heap will be automatically collected in the following situations:

  • Allocations exceed the large object heaps threshold.
  • System is in a low memory situation.
  • System.GC.Collect is called on generation 2.

The problem is that when the large object heap is collected, the memory for the objects is deallocated but the LOH is not compacted. Because the LOH is fragmented, you could potentially get SystemOutOfMemory exceptions thrown if there isn't a space big enough for your object on the LOH.

Techniques such as object pooling are commonly used to improve performance of the LOH. http://en.wikipedia.org/wiki/Object_pool_pattern

Source: http://msdn.microsoft.com/en-us/magazine/cc534993.aspx

UPDATE: .Net 4.5.1 will allow you to do on-demand compaction of the LOH within your application using the GC.Collect API.

like image 98
Yussuf Burke Avatar answered Oct 04 '22 18:10

Yussuf Burke


The GC in later versions, but more precisely 4.5, runs asynchronously for generations level 0 and 1. This has highly reduced the impact of GC.

If your objects are short-lived they should not pass from generation level 0 most of the time. Level 0 is the fastest generation to clean up by the GC.

Bottom line, I would not consider prematurely optimizing my code for fear of GC performance.

Premature optimization is the root of all evil by DonaldKnuth

Personally, i'd recommend this article for a deeper understanding

like image 41
Luis Filipe Avatar answered Oct 04 '22 16:10

Luis Filipe