Memory related Issues with Strings or Garbage Collection

You’re right, it is creating a lot of garbage. My fault, I really thought StringBuilder was more garbage friendly than what I’m seeing.
Replacing AppendFormat with Append (_currentMusicTime.Minutes). Append (“:”).Append (_currentMusicTime.Seconds) reduces the garbage a bit, but not significatively (And you’d still have to format it)

If your game is as string heavy as it seems for the screenshot, my suggestion would be either creating your own string class (not hard, only a PITA to replace it everywhere) or using something already created like :

I have my own too for my games, but unfortunately it’s not in a decent state to be shared : (

There are also other tips to avoid garbage creation. In example, the string you’re creating (e.g. 03m:15s ) only needs to be recreated once every second. You can cache the string, and change it only when the seconds change. This would reduce the creations from 3000 every second to 1 every second.

In the screenshot menus, you could print the strings once (as they’re all probably constant) and save into a list, and then reprinting those strings. Unfortunately all those tricks will dirty your code a lot, so I’d go with a No Garbage string unless it’s a very small problem like the time printing issue.

2 Likes