为什么javascript全局变量会导致大量分配?

时间:2013-10-20 23:08:23

标签: javascript garbage-collection

在下面的代码中,我使用变量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);
    ...
};

0 个答案:

没有答案