JavaScript performance - access to global variables [part 1]

Michael Schwarz on Friday, November 17, 2006

While reading several posts about JavaScript performance [1 [1]] [2 [2]] I did a simple test, too. My first part will compare Firefox and IE7 using global variables compared with local ones.

var x = {"FirstName":"Michael"};

function test1() { return x.FirstName; }

function test2() { var xx = {"FirstName":"Michael"}; return xx.FirstName; }

When running this JavaScript test on my machine I get for the first test a duration of 31msec for 10000 invokes, both in IE7 and Firefox. The second test needs about 78msec in both web browsers, very happy to see that IE7 is running at the same speed. Sometimes I get Firefox a little bit faster which may be a problem that the JavaScript Date object is not perfect when doing time measurements. But the next I tried is to use window.x.FirstName instead of only x.FirstName for the global variable. In Firefox I get everytime the same duration like the first test, but in IE7 I get 140msec which means that it is four times slower!

function test3() { return window.x.FirstName; }