这会导致性能泄漏还是别的什么?

时间:2014-12-14 00:33:50

标签: javascript performance memory-leaks

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

尝试将速度设置为快速,并注意蛇在击中食物后如何变得非常慢。在击中食物10次后,它的速度非常慢。必须有某种类型的性能泄漏,我找不到。

以下是蛇击中食物时执行的代码块:

    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

关于该程序的一些事情导致一切都变慢。知道为什么吗?

1 个答案:

答案 0 :(得分:0)

如果您使用的是Chrome或Firefox,则可以在console.time中包含ceratin操作,以查看哪一个导致了问题。我建议:

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');
}

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