Hi MonoGame Community,
I have currently been trying to do a lot of optimization on a game I am working on and ran a Memory profiler to see where there could be issues.
I have reduced the issues to just mainly strings being created constantly. One example I can give you is this segment of code:
if (ScreenManager.Instance.bShowMusicInfo)
{
musicBackUI.Draw(spriteBatch);spriteBatch.DrawString(TextManager.Instance.Chewy_32, _songString + ScreenManager.Instance.Music.currentSong.Name, new Vector2(80, 2160 - 170), Color.White); _currentMusicTime = TimeSpan.FromSeconds(ScreenManager.Instance.Music.CurrentMusicTime); _totalMusicTime = TimeSpan.FromSeconds(ScreenManager.Instance.Music.countDuration); _thisCurrentTimeString = String.Format("{1:D2}:{2:D2}", _currentMusicTime.Hours, _currentMusicTime.Minutes, _currentMusicTime.Seconds); _thisTotalTimeString = String.Format("{1:D2}:{2:D2}", _totalMusicTime.Hours, _totalMusicTime.Minutes, _totalMusicTime.Seconds); spriteBatch.DrawString(TextManager.Instance.Chewy_24, _thisCurrentTimeString, new Vector2(80, 2160 - 120), Color.White); spriteBatch.DrawString(TextManager.Instance.Chewy_24, " / " + _thisTotalTimeString, new Vector2(170, 2160 - 120), Color.White); }
It is not the only area where there are strings constantly being created each frame but if I enable the music display this code will run and the number of strings being created increases and causes a Garbage Collection say every 4 seconds.
I have tried multiple ways including a StringBuilder but the way I went about it was to use one StringBuilder _string and I was constantly Appending and Clearing each update and had the same string counts.
My question would be, is there a way to display these strings still onscreen and update when the data changes without there being massive amounts of strings to be created and causing the GC to fire so many times?
Or could someone educate me on these issues and the right way to approach it?
I have checked out willmotil’s MgStringBuilder at No Garbage Text ( MgStringBuilder ) But I am unsure how to utilize.
Any help is appreciated