Performance: using an array in an object namespace and local array

I played with javascript performance optimization and found something interesting. Here is the code:

function gObject() {

    this.obj = [];
    this.LIMIT = 100000;

    this.doLoopLocal = function () {
        var o = [];
        for (var i=0;i<this.LIMIT;i+=1) {
            o.push(i);
        }
        return o;
    };      

    this.doLoopObject = function () {
        this.obj = [];
        for (var i=0;i<this.LIMIT;i+=1) {
            this.obj.push(i);
        }
    };
};

var g = new gObject();

console.time('Using Local array');
g.doLoopLocal();
console.timeEnd('Using Local array');

console.time('Using Object array');
g.doLoopObject();
console.timeEnd('Using Object array');

When I run it, the log tells me that using local arrays is slower than using an array defined in the object namespace. The difference is significant - from 8 to 10 times! (FF 18.0.1)

Using Local array: 16ms
Using Object array: 2ms

Screenshot: enter image description here

I have always assumed that using objects defined locally inside a function is faster, but this experiment shows me the wrong way. Why is this happening?

: script Firefox, - , : . - Firebug, - . - .

+5
1

, , , .
, ? , doLoopObject this.obj, , "", : , . . , .
, JSPerf, , , Firefox, : : . , , , var ( ). , push() . , .
, , - .

, , , FF/Safari...

, : .

, , "", , myArray [lastIndex-1] = 0, , : .

+1

All Articles