【问题标题】:Reduce resource usage of this JS program?减少这个 JS 程序的资源使用?
【发布时间】:2020-09-17 13:41:51
【问题描述】:

我编写了以下 JS 程序,我使用 node 从命令行运行它。

//step one: create an array of remaining creatures
var remainingCreatures = [];

//some config variables:
var amt = 1000; //amount of creatues generated
var maxhlt = 1000; //max value for creature health stat
var minhlt = 100; //min value for creature health stat
var maxatk = 100; //max value for creature attack stat
var minatk = 1; //min value for creature attack stat

function remove(target) { //helper function to easily remove creatues from the array
  var index = remainingCreatures.indexOf(target);
if (index > -1) {
  remainingCreatures.splice(index, 1);
}

}

//generate creatures
//each creature has an Attack, Health, and Aggressiveness , as well as Instabillity, the average of the three
//A creature's Instabillity is added to the attack points of its opponent in fights.
for (var i = 0; i < amt; i++) {
  var atkVal = Math.floor((Math.random() * maxatk) + minatk);
  var hltVal = Math.floor((Math.random() * maxhlt) + minhlt);
  var insVal = (atkVal + hltVal) / 2;

  remainingCreatures[i] = {num: i, atk: atkVal, hlt: hltVal, ins: insVal, fts: 0, ihlt: hltVal};
}
console.log(amt + " creatues generated, starting melee...");



function fight(cr1, cr2) { //function to handle fighting, randomly creates creature pairs and has them fight
  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(b);
    } 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(a);
    }
    }
  }
  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(remainingCreatures[Math.floor(Math.random() * remainingCreatures.length)], remainingCreatures[Math.floor(Math.random() * remainingCreatures.length)]);
}

console.log(" ");
console.log("[WIN] Creature #" + remainingCreatures[0].num + " has won!");
console.log("Starting array size was " + amt + " creatures")
console.log(remainingCreatures[0]);

由于某种原因,当amt 设置为非常大的数字(例如一百万)时,这开始减慢并最终窒息。作为参考,这是将生成并添加到数组中的对象的数量 - 正如您可能在代码中看到的那样,该数组会循环很多次。但即使有一百万个对象,每个对象也只有大约 80 个字节,最大值。而且这个程序所做的计算是非常基础的。

所以我的问题是:为什么运行这个程序会占用大量资源?如何在不大幅改变程序功能的情况下修复或缓解它?

【问题讨论】:

    标签: javascript arrays node.js resources resource-management


    【解决方案1】:

    首先,一百万的任何事情都会对性能造成影响,无论多么小。 另一个问题是你的设计本质上是低效的。

    查看您的remove() 函数。它首先找到元素的索引,然后将其删除。如果该数组中有 100 万个元素,平均而言,它需要将传递的值与 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));
    
    

    (See this link 获取有关该评论的信息。)

    【讨论】:

    • "它需要将传递的值与 500,000 个元素进行比较,以便在删除之前找到它",然后删除可以触发数组的前向洗牌以关闭差距。地图/集可能更有效。
    • 我应该注意到 cr1 和 cr2 是从数组中随机选择的,这可能会干扰 101arrowz 传递索引的建议,因为我实际上并没有认识他们。
    • @VLAZ 事情是,集合是 ES6,这显然不是 ES6,所以这是我建议使用数组的唯一原因。否则套装绝对优越。此外,进行一次 O(n) 操作仍然比两次好。 (但 OP 应该尝试使用 ES6,它好多了)
    • @TheDeveloperNextDoor 再次阅读我给出的代码。您将随机 indices 传递给函数,而不是随机值。所以它有效。还可以查看现在传递给remove 的内容。
    • @101arrowz 谢谢,这很有帮助。我必须更改remove() 以在其if 语句中使用target 变量而不是index 变量才能正常工作,对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多