I profiled my XNA game project today using the XNA Framework Remote Perf Monitor and discovered that I was generating about 8000 more manage objects per second than I was expecting to.
It turns out that this code was generating 7400 managed objects per second:
text[0] = "FPS: " + fps.FPS.ToString();
text[1] = "charPos: " + charPos.ToString();
text[2] = "tLOD: " + tLOD.ToString();
text[3] = "tTris: " + tTris.ToString();
text[4] = "tBlocksDrawn: " + tBlocksDrawn.ToString();
text[5] = "tBlocksCulled: " + tBlocksCulled.ToString();
text[6] = "drawCodeTime: " + drawCodeTime.ToString();
A complicated optimization for code that isn’t even going to get compiled into the release build would be silly. The easiest fix here is to only periodically update the content of these strings (say, once per second, instead of once per frame.)
Also, some of the garbage generation could be reduced by separating the arrays into one array for the static strings “drawCodeTime: ” for example and then drawCodeTime.ToString() in a separate string. That would still leave thousands of objects per second created, sadly.
If you have a game that relies on many string conversions, your best bet is to use StringBuilder objects (which have predefined size) and replace subsections of those strings with the new string using the .Replace method that StringBuilders have built-in.
#1 by Gavin Pugh on -
Quote
Hi, I stumbled across this article from a web search.
A few months back I published some articles which delve into some methods to avoid garbage when working with strings. Particularly the ones you mention in this post; they would be addressed by using something similar from this:
http://www.musictomakegamesby.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/
Cheers.