Во-первых, миллион чего угодно скажется на производительности, даже если она мала. Другая проблема заключается в том, что ваш дизайн изначально неэффективен.
Посмотрите на свою remove()
функцию. Сначала он находит индекс элемента, а затем удаляет его. Если у вас в среднем один миллион элементов в этом массиве, ему нужно будет сравнить переданное значение с 500 000 элементов , чтобы найти его, прежде чем он сможет удалить. Есть один простой способ исправить это; передавать индексы напрямую, а не использовать .indexOf
.
function fight(ind1, ind2) { //function to handle fighting, randomly creates creature pairs and has them fight
var cr1 = remainingCreatures[ind1];
var cr2 = remainingCreatures[ind2];
function attack(a, b) {
console.log("[ROUND 1] Creature 1 (#" + a.num + ") is attacking first.");
b.hlt = b.hlt - (a.atk + b.ins);
console.log("[HIT] Creature #" + b.num + " health reduced to " + b.hlt);
if (b.hlt <= 0) {
console.log("[DEATH] Creature #" + b.num + " Eliminated");
remove(ind2);
} else {
console.log("[ROUND 2] Creature 2 (#" + b.num + ") is attacking second.");
a.hlt = a.hlt - (b.atk + a.ins);
console.log("[HIT] Creature #" + a.num + " health reduced to " + a.hlt);
if (a.hlt <= 0) {
console.log("[DEATH] Creature #" + a.num + " Eliminated");
remove(ind1);
}
}
}
console.log("[FIGHT] Pair generated: Creature #" + cr1.num + " and Creature #" + cr2.num);
cr1.fts++;
cr2.fts++;
if (cr1.ins <= cr2.ins) {
attack(cr1, cr2);
} else {
attack(cr2, cr1);
}
}
for(;true;) {
if(remainingCreatures.length == 1) break;
fight(Math.floor(Math.random() * remainingCreatures.length), Math.floor(Math.random() * remainingCreatures.length));
}
Существует не так много других способов легко улучшить производительность, но одного этого должно быть достаточно. Однако, чтобы сделать ваш код более читабельным, подумайте о замене этого:
for(;true;) {
if(remainingCreatures.length == 1) break;
fight(Math.floor(Math.random() * remainingCreatures.length), Math.floor(Math.random() * remainingCreatures.length));
}
на это:
// Consider using === and !== as best practice, but not necessary here
while (remainingCreatures.length != 1)
fight(Math.floor(Math.random() * remainingCreatures.length), Math.floor(Math.random() * remainingCreatures.length));
( См. Эту ссылку для получения информации об этом комментарии. )