JSLitmus isn't testing what it appears to be testing.
In the 'use instance var' case, take a look at what "this" is inside the
test function. I'll bet it's the window object. That is the reason it's so
much slower in Firefox. I didn't try it in IE, but the difference is
probably even more dramatic there.
It's not surprising that there is little difference in Chrome, with its
completely different architecture.
If 'this' a native JavaScript object, it's still slower to reference
"this.foo" than it would be to reference "foo", but not by such a great
difference.
Compare with this test that provides known values of "this":
var total = 1000000;
function Test() {}
Test.prototype.one = function() {
var t1 = +new Date;
var n = total;
var x = 0;
while( n-- ) x++;
var t2 = +new Date;
console.log( ( t2 - t1 ) / 1000 );
};
Test.prototype.two = function() {
var t1 = +new Date;
var n = total;
this.x = 0;
while( n-- ) this.x++;
var t2 = +new Date;
console.log( ( t2 - t1 ) / 1000 );
};
test = new Test;
test.one();
test.two();
test.one.call(window);
test.two.call(window);
In an example run, that logged these values to the Firebug console:
0.051 - test.one()
0.199 - test.two()
0.052 - test.one.call(window)
2.408 - test.two.call(window)
As you can see, test.two() is several times slower than test.one() when it's
called as a method of the test object, but dramatically slower when it's
called as a method of the window object.
-Mike
> From: howardk
>
> I've been experimenting with several different coding styles
> for plug- ins. Lately I've been curious about the difference
> in performance between using local variables vs. instance
> variables for storing state. JSLitmus, while not itself
> jQuery-based, has just given me the answers I've been looking
> for. I found them a bit surprising:
>
> http://www.fatdog.com/litmus_tests/InstanceVsLocalTest.html
>
> (Apologies for the color scheme! :-)
> Howard
>