Guidance on C# memory management #9916
Labels
content:new page
Issues and PRs related to creation of new documentation pages for new or undocumented features
enhancement
topic:dotnet
Your Godot version:
Godot 4.3
Issue description:
I believe that it would be very helpful to add a section with general guidance for memory management in C#. There is already a section in the docs dedicated to memory management here, but it only discusses memory segmentation in general, and is aimed at developers who want to contribute to the development of the engine itself, not at users of the engine. The conclusion is:
My main question that I would like to see answered is: Does this apply to C#? If we're doing many small heap allocations, the garbage collector will eventually run. Even if memory segmentation is not an issue, could this cause performance issues?
I've found conflicting information online about the impact of such allocations on garbage collection and overall performance. Some sources suggest that modern garbage collectors handle these situations efficiently, but the Unity documentation explicitly says:
I bumped into this issue when I found out that the
Send
method in C# ofENetPacketPeer
requires abyte[]
argument (see godotengine/godot#71727). This array must have the exact length of the network packet that I want to send, so this requires an allocation of a temporary array, and there is no way to work around this with a memory pool. Should this API be updated at some time to be more memory efficient, or is there a general consensus that the garbage collector is fast enough that we can afford to allocate these small arrays for every API call, in particular because those are short-lived allocations?Other questions that I would like to see answered:
ArrayPool<T>
andMemoryPool<T>
. When should these be used?I understand that this is a very broad topic and it won't be possible to give definitive answers to these questions. However, what concerns me is this: If I continue making hundreds of slightly suboptimal design decisions during game development, what happens if I run into memory performance issues in one or two years that are possibly difficult to debug and pin down? Then I might be forced to do countless small refactorings all over the place - I want to avoid that.
In other words: We can tell a beginner programmer not to put all global state into one all-knowing singleton. Or before creating subclasses in their model, to try composition first. This advice will probably lead to better overall design decisions and more maintainable code. Can we say similar things about C# memory management in Godot projects?
The text was updated successfully, but these errors were encountered: