在 node.js 服务器端代码优化方面寻求帮助

问题描述

const Generator = require('./js/generator');
items=[]
amount=largnumber
while(items.length<amount){
    //inside this loop there is multiple of these so it makes say 100 per run to speed up populating the array
enter code here
 items.push(new Generator(arg,arg,arg))
...

}
console.log("done")
// after here goes the real code as above takes about an hour some times due to the amount of new items to push 
// performs an update function on each thing passing its max values for height & width the items and g which is [0,0] for Now.
 function update(){
items.forEach((p,i) => { p.update(items,maxh,maxw,g) if(i>=gens.length-1){setTimeout(function () {update()},10)}
}

注意这里使用的超时只是为了停止递归阻塞,以便其他事情可以对接我还尝试设置一个间隔,每 100 毫秒调用一次更新函数,尽管它阻塞了节点动脉,但两者都在没有超时的情况下工作。

generator.js 中的 update 部分是一个生成器类,其构造函数为 this.foo=bar

update(s,width,height,g){

if(this.location[0]+this.radius>height)
this.veLocity[0]=(this.veLocity[0]*-1)*0.95,this.location[0]=height-this.radius;
if(this.location[0]-this.radius<-height)
this.veLocity[0]=(this.veLocity[0]*-1)*0.95,this.location[0]=this.radius;
if(this.location[1]+this.radius>width)
  this.veLocity[1]=(this.veLocity[1]*-1)*0.95,this.location[1]=width-this.radius;
  if(this.location[1]-this.radius<-width)
  this.veLocity[1]=(this.veLocity[1]*-1)*0.95,this.location[1]=this.radius;

if(this.location[2]>height){
  this.veLocity[2]=(this.veLocity[2]*-1)
    this.location[2]=height-this.radius;
}
if(this.location[2]<-height){this.veLocity[2]=(this.veLocity[2]*-1)
this.location[2]=-height+this.radius;}

var _radians = Math.atan2((this.location[1]+this.veLocity[1])-this.location[1],(this.location[0]+this.veLocity[0])-this.location[0]);
var _degrees = _radians * ( 180 / Math.PI );
this.rotation = _degrees;
this.updatespeed=(new Date()-this.lastupdate)/1000
this.lastupdate=new Date()
       this.location[0]+=this.veLocity[0]*this.updatespeed
       this.location[1]+=((this.veLocity[1])-g[1])*this.updatespeed
    this.location[2]+=this.veLocity[2]*this.updatespeed

}

更新函数本身完成得非常快,在测试数组中的 250000 个项目时,似乎只用了不到 1 秒的时间来迭代它们

我的问题是,如果我超过 500000 次,遍历它们的循环需要更长的时间来计算,是否有更好的方法调用所有内容的更新函数

我在想生成器本身会创建一个时间间隔来更新自己吗?但也认为这会快速阻塞节点队列...... 我遇到了最大内存大小的问题,就像一个巨大的数组所预期的那样。 250 万个项目需要大约 19GB 的内存,我已经解决了......

我尝试使用 items.map(x=> x.update()),因为我觉得使用 map 比 foreach 快,但是在排斥测试中,map vs foreach 在 250k 项时慢了大约 3*,并且缩放比例相同。

我已经运行了 250k 个项目,我相信它们的增量时间每个大约 1 秒,有时它的 0.3 秒取决于运行的其他代码,我猜..... 我假设如果我去 250 万它的 10 秒和 2500 万将是 100 秒......不确定它是否会像那样迭代,因为它可能是 10 倍的增加,由于指数检查,时间增加了 100 倍。

难看的代码我确定

感谢您的关注和帮助 对不起,如果它太难看/没有正确编码/右下角对你的眼睛来说很糟糕,请不要看着它而死。

作为旁注,我还有一个 socket.io 东西在那里运行,所以我可以访问一个 url,它会生成一个东西并定期更新网页,效果很好,它按预期每秒钟更新一次,因此不会被阻止显示项目增量时间 image to what i see in the url

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)