C# and .Net Garbage collector performance

2019-03-17 19:21发布

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.

2条回答
Rolldiameter
2楼-- · 2019-03-17 20:07

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

查看更多
Lonely孤独者°
3楼-- · 2019-03-17 20:15

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.

查看更多
登录 后发表回答