I am writing a simulation which has an update loop that's called every frame. In the update function, I have millions of objects to update, so it looks like this.
public void Update(float deltaTime)
{
Time += deltaTime;
foreach (SimulationObject obj in objects.ToArray())
obj.Update(deltaTime);
}
where objects is
List<SimulationObject> objects = new List<SimulationObject>();
and is populated at program initialization time.
You can probably see objects.ToArray() makes a copy of this huge list every frame then the copy gets garbage-collected. This causes huge performance issue for me. For a run of about 2 minutes, the garbage collected reaches about 2G. Since the list of this objects is being asynchronously modified in the background by some third-party library, it seems I can't remove ToArray().
I am wondering if there's a good way to reduce garbage collection, either avoid copying or reuse the allocated space?
I am new to C# and tried searching for answers, but was not able to. If this is a duplicated post, I apologize.