1

在下面的代码中,我使用变量 diff 来存储粒子的目标位置与实际位置之间的差异。当我将该值存储到本地“var diff”中时,我的内存分配不会增长。如果我使用在函数外部声明的全局“var diff”或完全省略声明,我会看到巨大的内存分配。为什么使用全局变量会导致大量分配?

我已经离开了工作,非代码评论。

附带说明一下,当全局设置时,下面的粒子变量不会改变分配量。在这两种情况下,代码都会执行所需的任务。

在 Chrome 版本 30.0.1599.101 m 上测试

代码:

//Could also declare global for diff or particle out here with no change.
LoadingScreen.prototype.Update = function(delta)
{
    var size =  this.totalParticles - 1;
    while(size--)
    {
        //Works perfectly
        var particle = this.particleSystem.geometry.vertices[size];
        //Also works perfectly with no extra allocations.
        /* particle = this.particleSystem.geometry.vertices[size]; */
        if(size >= this.row)
        {
            //Works perfectly
            var diff = particle.gridy - particle.y;
            //Causes huge memory allocations garbage collection and the like
            /* diff = particle.gridy - particle.y; */
            if(diff < 5 * delta)
                particle.y = particle.gridy;
            else
                if(particle.y != particle.gridy)
                    particle.y += 500 * delta;
        }
    }
    this.row = this.totalParticles * (loadStatus.left / loadStatus.total);
    ...
};
4

0 回答 0