Memory related Issues with Strings or Garbage Collection

As others have mentioned, the idea is to limit changes of memory to cases where it needs to change.
However there is trick which I believe no one has mentioned yet.

A string in C# is an immutable object which is allocated and tracked on some memory heap by the garbage collector (GC). The immutability means to modify a string a new string has to be created. The consequence of doing that however is that a new allocation has to happen. What we really want in is to avoid dynamically allocating memory in loops. Since a game is a loop, we want to avoid dynamically allocating memory in games every frame. Best performance can be achieved if allocation of memory can happen once at startup or at strategic times like loading a level, but not every frame (iteration of a loop).

The idea with StringBuilder is it’s an abstraction to manipulate an intermediate buffer of char values and “build” the string from this buffer. Note that in .NET a char is 2 bytes. Using StringBuilder allows to use the intermediate buffer directly. SpriteBatch.DrawString even has an overload for accepting a StringBuilder as a parameter allowing the intermediate buffer to be used directly instead of having to create a string from the buffer. Great! We can use a StringBuilder to achieve mutable strings without dynamic allocation. Sadly, some methods of StringBuilder allocate memory. Can we do better?

Well yes, but it’s not pretty. We can use our own buffers of char and create our own logic for manipulating and drawing these buffers. This is where the No Garbage Text ( MgStringBuilder ) and others do. For example lets say you want to draw the string “FPS: 1000” to the screen. If we fix the buffer to be a certain size we would need to know how long the string can possibly get. So lets say we have the format: “FPS: NNNNNN”. From here every frame we can simply change the contents of the buffer (mutate) to match what we want to render. Simple, effective, but not intuitive from how .NET traditional looks at how to solve problems with strings.

1 Like