javascript - 这会导致性能泄漏还是其他原因?

标签 javascript performance memory-leaks

我正在制作一款游戏,您可以在这里测试:http://jaminweb.com/projs/snakegame.php

尝试将速度设置为,并注意蛇在碰到食物后如何变得非常慢。撞击食物 10 次后,它变得 super 慢。一定存在某种类型的性能泄漏,但我很难找到。

以下是当蛇碰到食物时执行的代码块:

    if (this.boxCollision(BBhead, BBfood))
    {
         this.moveFood(this.canvHeight, this.canvWidth);
         this.score += 10;
         document.getElementById("snake-score-div").innerHTML = this.score.toString();
         addLink = true;
    }
    if (addLink)
        this.body.push(this.body[this.body.length - 1].clone());

其中函数moveFood

定义
        snakegame.prototype.moveFood = function()
        {   
            var bbf = this.food.getBBox(); // bounding box for food
            do 
            {
                // tx, ty: random translation units 
                tx = randInt(0, this.canvWidth / this.linkSize - 1) * this.linkSize - bbf.x;
                ty = randInt(0, this.canvHeight / this.linkSize - 1) * this.linkSize - bbf.y;
                // translate copy of food
                this.food.translate(tx, ty);
                // update bbf
                bbf = this.food.getBBox(); 
            } while (this.hitSnake(bbf));

        }

以及函数clonetranslate来自这个库:http://raphaeljs.com/reference.html

该过程的某些原因导致一切变慢。知道为什么吗?

最佳答案

如果您使用的是 Chrome 或 Firefox,您可以将某些操作包装在 console.time 中,以查看哪个操作造成了问题。我建议:

if (this.boxCollision(BBhead, BBfood))
{
     console.time('Moving food');
     this.moveFood(this.canvHeight, this.canvWidth);
     console.timeEnd('Moving food');

     console.time('Increasing score');
     this.score += 10;
     console.timeEnd('Increasing score');

     console.time('Updating score display');
     document.getElementById("snake-score-div").innerHTML = this.score.toString();
     console.timeEnd('Updating score display');

     addLink = true;
}
if (addLink) {
     console.time('Body clone');
     this.body.push(this.body[this.body.length - 1].clone());
     console.timeEnd('Body clone');
}

然后检查您的控制台并观察数字。

关于javascript - 这会导致性能泄漏还是其他原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465133/

相关文章:

c - 内存使用不足会导致内存泄漏吗?

javascript - Bootstrap Datetimepicker 更改事件未触发

ios - 如何有效地分析 Xcode 中的丢帧?

sql - SQL中如何连接多个select语句

java - 何时以及如何将 java 类加载器标记为垃圾收集?

javascript - Kineticjs 会导致内存泄漏。舞台被摧毁后不释放

javascript - IonViewDidLoad 或 ionViewWillEnter 中的 Ionic 3 react 形式不起作用

javascript - 我想在 Openlayer map 上单击鼠标添加这些圆圈

javascript - Vue 属性未定义

c# - 我可以忽略 WCF 异步 EndXXX 调用吗?