1

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.

2
  • While both of the functions "work", it's an inappropriate use of the .map function. Maybe this helps to understand it better: en.wikipedia.org/wiki/Map_function. Commented Jun 15, 2013 at 20:01
  • The question is moot. You are using the map method wrong. It's used to loop one array and return another, but you are using it as the each method. Commented Jun 15, 2013 at 20:01

2 Answers 2

3
function adeneos_object() {
    obj[ keyx ] = $.map($( selector ),function(el){return el.value;});
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is how you use the map method.
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.