I have a project that works with a large amount of objects of the same type.
For now I use List<Person>
, but it seems that looping through this list is hard when I have about 1 000 000 items.
In the loop, each Person
has a method called and there are randomly generated new items, and some items are deleted.
What can I do to optimize this loop ? Should I change the collection type, or move items to database ?
This is how the loop looks like:
while (_worldIsLiving)
{
int beginningPopulation = WorldPopulationNumber;
for (int i = 0; i < beginningPopulation; i++)
{
_worldPopulation[i].InvokeSkills(this);
}
// Remove dead persons
for (int i = 0; i < WorldPopulationNumber;)
{
if (_worldPopulation[i].IsDead()) _worldPopulation.RemoveAt(i);
else i++;
}
WorldCycles++;
if (_hasStopCondition && (WorldPopulationNumber >= WorldMaximumPopulation || WorldPopulationNumber == 0))
Destroy();
}
In _worldPopulation[i].InvokeSkills(this);
new persons can be generated.
Skill has a chanceToBeInvoken
and chanceTobeInherited
fields.