Is there a performance advantage when using an object literal over a self-created constructor?

Question

Is there a performance advantage when using an object literal over a constructor created by yourself?

Examples

Object Literal:

var foo = { //... }; 

Self created constructor:

 var foo = new function () { //... }; 
+7
performance javascript object
source share
1 answer

Yes (the object literal will be faster), but they differ significantly in implementation 1 and represent different goals. The constructor form โ€œshould do a lot more stuffโ€, while the literal form can also be more optimized - this is a definition (as yet an unfixed set of properties), and not a sequence of statements.

Even if the micro-benchmark (which is interesting, thanks to Arun!) Can show that one of them is โ€œmuch slowerโ€, t Matter in real program 2 since the amount of relative time spent on any design does not come close.


1 When a constructor is used, a prototype should be presented . This does not apply to the object literal due to its fixed chain behavior.

Each object created by the constructor has an implicit reference (called the prototype of the objects) to the value of the constructor property "prototype".

Other overheads include creating a new execution context, copying additional properties, and even checking the return value. (In the published case, he must also create a new one-time functional object before he can use it as a constructor, which himself adds additional additional overhead ).

2 I am sure there are counter examples. But for such cases, I can only hope that the problem was carefully compared with all the identified and resolved bottlenecks.

+10
source share

All Articles