Is there a performance advantage in using an object literal over a self instantiated constructor?
Object literal:
var foo = {
//...
};
Self instantiated constructor:
var foo = new function () {
//...
};
To my mind object literals have two advantages. One they are used by many plugins such as jQuery so people are familier and they are easy to read. Making them easy to pass through data into a plugin. It's easy to create both public and private methods....
Objects created using object literals are singletons. This means when a change is made to the object, it affects that object across the entire script. Object defined with a function constructor let us have multiple instances of that object. This means change made to one instance, will not affect other instances.
Now the question is when should we be using Literal notation and constructor notation. The point is when we need only one instance with the same values then we can go with the literal notation else if we may need multiple instances, like the instance of a class, we can go for the constructor notation.
Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With