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 () {
//...
};
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 () {
//...
};
Share
Improve this question
asked Aug 13, 2013 at 0:55
AlertyAlerty
5,9558 gold badges41 silver badges62 bronze badges
2
- 2 see jsperf./object-notation-vs-constructor – Arun P Johny Commented Aug 13, 2013 at 1:01
-
Modified perf (see rev. 5) did not expect
Object.create
to be so slow! – Paul S. Commented Aug 13, 2013 at 10:39
1 Answer
Reset to default 10Yes (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.