sakurashinken
sakurashinken

Reputation: 4080

Is there a performance cost for the new operator in javascript?

In general is there a performance cost for method B:

Method A

 var foo = { 
      propertyA:
      ...
 };

 var SomethingSimilarToFoo = { 
      propertyA:
      …
 };

Method B

Var foo = function(){
       this.propertyA = ..
       …
}

foo1 = new foo(config);
SomethingSimilarToFoo = new foo(config);

Upvotes: 3

Views: 2832

Answers (1)

Oriol
Oriol

Reputation: 288230

See http://jsperf.com/methods-vs-instances

On the one hand, it seems that literal objects are much faster than instances on Firefox. Probably, the cause is that function calls are expensive.

On the other hand, instances are faster on some versions of Chrome.

Anyway, using instances without prototype is a bit useless. But using the prototype, instances can inherit properties (which means less memory) and you gain a lot of flexibility.

Upvotes: 2

Related Questions