0

In JavaScript:

Example 1:

var x = {}; x.a = 10;

Example 2:

var x = {}; x = {a: 10};

Is there any difference between Example 1 & 2 on the basis of performance, considering that a lot of properties need to be attached to var x, and not just a.

Which is more efficient?

1
  • 3
    x = {a: 10}; replaces the old object that x was pointing to with {a: 10}. There is no point to initializing x to equal {}. Commented Dec 10, 2014 at 11:51

1 Answer 1

6

Go for option 3:

var x = {
    a: 10,
    b: 20,
    // etc
};

Don't declare x as a empty object, only to replace it with an object with an a property.

When you need to set a large amount of properties on a object, using a object literal like that is more efficient than adding every single property separately. However, the difference will be negligible.

The disadvantage of option #1 is:
1 operation for every single property to add to the object, which will have an effect when larger amounts of properties are required.

The disadvantage of option #2 is:
You're declaring the object, then replacing it completely.

My suggestion simply adds all required properties to the object in one go, without replacing the variable.

Sign up to request clarification or add additional context in comments.

13 Comments

There wasn't option 3 in question.
@Vladimirs: so? What I'm saying is that neither of the options the OP posted are a very good idea. I'm suggesting an alternative to those 2 options.
@Cerbrus Option 3 does not hold when you have to add properties on the go. But your rest of the answer explains something.
@Vladimirs How do I pin a nail to my wall? With a spoon or with a fork? By your logic, you'd say the spoon, I'd say it's the hammer.
|

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.