7

Question

Is there a performance advantage in using an object literal over a self instantiated constructor?

Examples

Object literal:

var foo = { 
    //... 
};

Self instantiated constructor:

var foo = new function () {
    //...
};
2

1 Answer 1

10

Yes (the object literal will be faster), but they are subtly different in implementation1 and represent different goals. The constructor form "has to do a bunch more stuff" while the literal form can also be more highly optimized - it is a definition (of an as-of-yet-fixed set of properties), and not a sequence of statements.

Even though a micro-benchmark (which is interesting, thanks Arun!) might show one being "much slower", it Just Doesn't Matter in a real program2 as the amount of relative time spent in either construct approaches nothing.


1 When a constructor is used a prototype must be introduced. This is not the case with an object literal due to it's fixed chain behavior.

Every object created by a constructor has an implicit reference (called the object’s prototype) to the value of its constructor’s “prototype” property.

Other overhead work includes creating a new execution context, copying over additional properties, and even checking the return value. (In the posted case it also has to create a new one-off function object before it can even use is as a constructor which itself adds some additional overhead).

2 I'm sure there are counter-examples. But for such cases, I can only hope that the problem has been thoroughly benchmarked with all other bottlenecks identified and removed.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.