javascript - Is there a performance advantage in using an object literal over a self instantiated constructor? - Stack Overflow

QuestionIs there a performance advantage in using an object literal over a self instantiated constructo

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
Add a ment  | 

1 Answer 1

Reset to default 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744767159a4592531.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信