Reputation: 1326
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
Reputation: 15895
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
Reputation: 318372
function adeneos_object() {
obj[ keyx ] = $.map($( selector ),function(el){return el.value;});
}
Upvotes: 3