Alex
Alex

Reputation: 632

JavaScript: replace param with a local variable?

If I have a funtion like this:

function xyz(b)
{
    for(var i = 0; i < b.length; i++)
    {
        // do something with b items...
    }
}

... wouldn't it be more memory-friendly if I were to assign b to a local variable inside of that function before working with its items?

function xyz(b)
{
    var c = b;

    for(var i = 0; i < c.length; i++)
    {
        // do something with c items...
    }
}

Upvotes: 0

Views: 49

Answers (1)

Asaf David
Asaf David

Reputation: 3297

In your example both b and c are local variables since they only exist in the function. So your code will actually be a bit less performant.

Side note - if you want your code to be more performant you should calculate c.length only once for the whole for loop. In your example you're calculating it for every iteration of the loop. Instead you can do as follows:

for (var i = 0, cLen = c.length; i < cLen; i++)

This way it calculates it only once before starting the loop.

Upvotes: 2

Related Questions