Nikki
Nikki

Reputation: 3674

Quick one about static local variables in js

I read you could simulate static local variables in js like this:

function count() {
count.i++;
}
count.i = 0;

Is storing 'i' as a property of 'count' faster than using a global? eg.

var i=0;
function count ()
{i++;
}

Just a performance comparison question.

Thanks.

Upvotes: 1

Views: 1565

Answers (2)

KooiInc
KooiInc

Reputation: 123016

Seems an externally stored value is faster. See this test. It matters if you assign count.i within the function or outside. Assigning it outside the function shows a small difference. I wouldn't worry about that.

You can also consider this to emulate something static (added to the jsperf-test, it's roughly as fast as assigning a global variable or an externally assigned count.i)

function counter(){
 var i = 0;
 return {
     count:    function(){i += 1;},
     toString: function(){return i;},
     valueOf:  function(){return i;}
 };
}

var foo = counter(), bar = counter();
foo.count();
bar.count();
bar.count();
console.log(bar); //=> 2
console.log(foo); //=> 1

Upvotes: 1

Guffa
Guffa

Reputation: 700910

Theoretically the global variable should be slightly faster than the property, as the property lookup needs another step.

However, performance can differ quite a lot between different browsers, and accessing variables and properties is such fast operations that any performance difference there will rarely matter. Most other things that you do in a script will take a lot longer.

Upvotes: 1

Related Questions