我有一個與大量相同類型的對象一起工作的項目。List <>循環優化
現在我使用List<Person>
,但是似乎在我有大約1 000 000個項目時循環遍歷這個列表是困難的。
在循環中,每個Person
都有一個被調用的方法,並且有隨機生成的新項目,並且有些項目被刪除。
我該怎麼做才能優化這個循環? 我應該更改集合類型還是將項目移動到數據庫?
這是循環的樣子:
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();
}
在_worldPopulation[i].InvokeSkills(this);
可以產生新的人員。
技能有chanceToBeInvoken
和chanceTobeInherited
字段。
迭代速度更快的唯一方法是使用普通數組,但這可能只會產生一個邊際差異。任何優化通常都在循環中的代碼中,而不是容器中。要回答這個問題,我們需要更多地瞭解循環中的代碼。 –
當你說「循環通過這個列表很難」你是什麼意思的「硬」?只需要幾個元素就可以輕鬆循環列表 - 只需要更長的時間。 – Enigmativity
項目存儲在內存中。 '人'擁有技能列表,每個技能都有機會被調用。 主循環中的代碼:我調用調用隨機技能的Person類中的方法。 @MatthewWatson 循環很難,因爲一個循環需要大量的項目需要一分鐘左右的時間。 @Enigmativity –