Posts tagged: GC

Garbage Collection Nightmares…

I was pushing Galactic Defense to the Zune today to do some minor version testing (I develop on the PC and then push to Zune for platform specific tests) and ran into some major problems. The GC was collecting about once an update which was slowing the game down tremendously. So I dug in and started searching my code.

One of the best ways to figure out where you are creating garbage (when no tool can do it for you) is just to start commenting things out. For starters, I commented out the draw code for my map. This worked, but not enough. I ended up adding a line that removed the InputManager from the component collection (effectively commenting out its update code) and I had it: 0 allocations per update.

So I looked at the draw code again and realized (with the help from guys in #xna) that I was using an enumeration in a Dictionary. A big no no since the framework allocates every time you do a lookup. A quick switch to ints (cast all lookups to integers) fixed that problem. Now onto the InputManager.

To make a long story short, I followed the trail and cornered this line of code:

1
if(!repeatKeys.Contains(button))

It is this line of code that actively makes sure that I have all the buttons in the repeatKey list so I can check and update the repeated keys later on. I removed this line of code and added the following:

1
2
3
4
5
6
7
8
9
10
11
12
bool found = false;
for (int i = 0; i < repeatKeys.Count; i++)
{
    if (repeatKeys[i] == button)
    {
        found = true;
        break;
    }
}
 
if (!found)
    repeatKeys.Add(button);

And now I am back to a normal amount of allocations (some for strings) per update. I wonder why Contains is causing an allocation. I am too lazy to figure that one out right now…

WordPress Themes