Marcus McLean
Marcus McLean

Reputation: 1326

Performance of modifying an array in an object: to use a variable, or not?

Consider the following JavaScript global object:

var obj = { key1: [ 'data1', 'data2', ... ], key2: [ 'data1, 'data2', ... ], ... }

Assume I have a function that needs to modify the array assigned to a specific key in obj. Is it more efficient to use a local variable for my computations and modify the array at the end of my function, or should I be modifying the array directly, since it's not deep within the object?

In essence, I am asking which function is more efficient:

function local_variable() {
    var foo = [];
    $( selector ).map(function() {
        foo.push( $( this ).val() );
    });
    obj[ keyx ] = foo;
}

versus

function global_object() {
    obj[ keyx ] = [];
    $( selector ).map(function() {
        obj[ keyx ].push( $( this ).val() );
    });
}

As always, if there is an even better way to do what these functions do, please enlighten me.

Upvotes: 1

Views: 94

Answers (2)

oleq
oleq

Reputation: 15895

jsPerf comes with help.

Apparently, accessing object's property each time (global_object) is slower that data acquisition and further assignment (local_variable).

However, as you see, it depends on the optimization strategy used by the particular browser (Firefox, almost equal).

Upvotes: 1

adeneo
adeneo

Reputation: 318372

function adeneos_object() {
    obj[ keyx ] = $.map($( selector ),function(el){return el.value;});
}

Upvotes: 3

Related Questions