Leah Zorychta
Leah Zorychta

Reputation: 13419

global variables javascript, which is faster "varname" or "window.varname"

var testvar = 'boat';

function testA() {

    console.log(testvar);

}

function testB() {

    console.log(window.testvar);

}

I know that if I don't put the "window." for my global variable, then javascript searches all the scopes from method testA onward until it finds the variable testvar, so if I do window.testvar instead does it make it faster because I'm directly telling javascript which scope to look in for the variable? Or slower because I'm first telling javascript to look for the window object and then the variable?

Upvotes: 1

Views: 1193

Answers (4)

Ian Nartowicz
Ian Nartowicz

Reputation: 11

Vedaant's jsperf was not helpful. It was only creating functions, not executing them. Try this one: http://jsperf.com/epictest/9. It too shows that not specifying window is faster. I also added a test to show that copying to a local variable is dramatically faster. Vary the loop counter to see that you win for anything more than a single reference to the global.

Upvotes: 1

Vedaant Arora
Vedaant Arora

Reputation: 217

I just made a jsPerf test for you, check it out at: http://jsperf.com/epictest. It seems that

function testA() {

   console.log(testvar);

}

is a bit faster.

Upvotes: 0

user188654
user188654

Reputation:

Try both of the codes below separately and see the results for yourself. Indeed this might not be the most accurate testcase however by avoiding all other manipulation and doing a simple assignment inside a long enough for loop it ought to be accurate enough.

I have to say I was also surprised to see that by not specifying window Chrome persistently reported about 20% faster execution for the second code.

CODE 1

// window.testvar testcase.
window.testvar = 'Hi there! I am a testvar!';
var tmp;
var start = new Date();
for(var i = 0; i < 1000000; i++){
    tmp = window.testvar;
}
var stop = new Date();
console.log('This took exactlly ' + (stop.getTime() - start.getTime()) + ' milliseconds!');

RESULTS:

  • 1695ms
  • 1715ms
  • 1737ms
  • 1704ms
  • 1695ms

CODE 2

// direct testvar testcase
testvar = 'Hi there! I am a testvar!';
var tmp;
var start = new Date();
for(var i = 0; i < 1000000; i++){
    tmp = testvar;
}
var stop = new Date();
console.log('This took exactlly ' + (stop.getTime() - start.getTime()) + ' milliseconds!');

RESULTS:

  • 1415ms
  • 1450ms
  • 1422ms
  • 1428ms
  • 1450ms

Tested in Chrome 20.0.1132.47.

Upvotes: 2

septemberbrain
septemberbrain

Reputation: 1008

Chrome has a useful javascript CPU profiler. Just create a loop to run the function several thousand times and start the profiler. I'm guessing that the difference is very small but this would be a good way to know for sure.

Upvotes: 0

Related Questions