Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the performance impact of setPrototypeOf on a new Object?

The MDN hints that using .setPrototypeOf() will have a bad influence on the future performance of your code.

I also read a few Questions about why changing the [[Prototype]] of an object will lower the performance. But none of the answers really explained whats going on in the background. So I wonder if this also applies for new Objects.

In particular I really like to do things like this:

var MyPrototype = {
    method1 : function(){...},
    method2 : function(){...},
    ...
};

var newObject = Object.setPrototypeOf({
    property : 1,
    property2 : 'text'                 
}, MyPrototype);

Unfortunately you can't do this with Object.create since it doesn't accept a plain object literal.

Does my use of setPrototypeOf also decrease the performance of the executing JS engine?

like image 777
Jovan Avatar asked Sep 07 '15 18:09

Jovan


1 Answers

If you fear (as apparently you should..) the performance impact of using Object.setPrototypeOf(), but want to keep your object creation syntax similar to how your code is structured, try this:

var MyPrototype = {
    method1 : function(){...},
    method2 : function(){...},
    ...
};

var newObject = Object.assign(Object.create(MyPrototype), {
    property : 1,
    property2 : 'text'                 
});
like image 113
Amit Avatar answered Nov 15 '22 20:11

Amit