javascript function scope, variable declaration

lets say that I have the following scenario:

var namespace = {};
(function($)
{
    $.extend(namespace, 
    {
        test1: function(someArray, someObj)
        {
             for(var i= 0, ii= someArray.length;i<ii;i++)
             {
                 var text = someObj[someArray[i]];
                 // do something with text
             }
        },
        test2: function(someArray, someObj,i,ii,text)
        /*
             see that the i,ii,text are  unused parameters,
             that will be used instead of variables
        */
        {
             for(i= 0, ii= someArray.length;i<ii;i++)
             {
                  text = someObj[someArray[i]];
                 // do something with text
             }
        },
    });
})(jQuery);

Now, the result of the test1 and test2 are the same... but what about the performance, memory usage... Is there any difference between declaring the i,ii, test variables in the two ways presented above ?

I think that the test2, for example, is probably more efficient because the variables are in the local function scope so after the function exits, the execution context is destroy, releasing the resources used for the arguments... the variables will not be assigned to the global object 'window'.

So what method is performing best? and why?


[Edit]

Thanks all for your answers !

There is no problem if the code has readability issues... I`m only interested now about the performance/memory usage.


If you do not declare your variables with var i then they become implicitly global.

Always declare your variables. If you did any benchmarking on that you would find that declared local variables are actually faster then implied global variables. Also you don't leak to the global state that way.

Benchmark!.

As you can see the performance is identical.

In terms of memory usage, local variables (test1) are probably better as the compiler doesn't have to remember that the function has 5 parameters.

But that's a nano optimisation If you care about performance differences of this caliber write assembly instead. Go for readable and maintanable code.

[Edit]

Didn't notice "local" variables in method parameter. That is a readability killer! Don't do that. You will find that test1 is probably still more efficient.


  • Why don't you profile your code?
  • The variables are also local in test1 . You are declaring them with var i . There is no difference between these methods.

  • The variables in "test1" are all declared with var , so they're not global. Those two should be essentially the same.

    链接地址: http://www.djcxy.com/p/64154.html

    上一篇: for循环与forEach性能在JavaScript和jsperf结果的可信度

    下一篇: javascript函数范围,变量声明