【问题标题】:Could this be causing a performance leak or is it something else?这会导致性能泄漏还是其他原因?
【发布时间】:2014-12-14 00:33:50
【问题描述】:

我正在制作一个你可以在这里测试的游戏: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

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

【问题讨论】:

  • 在“快速”上获得 150 分后,我没有看到任何明显的性能下降。您使用的是什么操作系统/浏览器?

标签: javascript performance memory-leaks


【解决方案1】:

如果您使用的是 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');
}

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

【讨论】:

    猜你喜欢
    • 2012-07-20
    • 2021-04-10
    • 1970-01-01
    • 2018-01-08
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多