I was working on a game with a lot of AI and noticed that my garbage collector was collecting objects 3-4 times a second which was really hurting performance and limiting the enemy count to 120 before the frame rate dropped. I profiled the code and found the culprit to be my collision detection code where I had a function being called multiple times a frame that was generating a list of projections onto axes. The code was like
public List<Vector2> foo()
{
List<Vector2> projections = new List<Vector2>();
// Calculate and return projections
}
There were a few other functions creating new lists every call as well and I switched out the generation of new lists each function call in favour of having a list of vector2s stored as a field of the class so that I am not calling new list every function call. This reduced the the garbage collections calls from 3-4 times a second to once every 10-20 seconds, allowing me to get 400-500 enemies on the map before frame rate dropped.
The new functions would have looked like:
public List<Vector2> foo()
{
// projections is now a field of this class so we just clear it each function call
projections.Clear();
// Calculate and return projections
}
My question is why does the List.Clear method incur way less garbage collections than List = new List()? I have done some research into what happens to items in a list when you call clear and it appears as if they should be garbage collected as well when they have no references anymore, so my items are being created inside the function so when that function exits and the list is cleared next call, shouldn't the previous items be garbage collected as well?
My understanding is that the items cleared should be garbage collected just like when I call List = new List. Clearly something else is going on as my garbage collections drastically reduced when I switched to List.Clear(). Here are the links I used for trying to understand whats happening to my list items.