Home >Web Front-end >JS Tutorial >Why Does Modifying an Object\'s [[Prototype]] Impact Performance?
Impact of Modifying an Object's [[Prototype]] on Performance
The Mozilla documentation for the standard setPrototypeOf method and the non-standard __proto__ property warns against mutating the [[Prototype]] of an object, emphasizing its detrimental impact on performance in modern JavaScript implementations.
However, this warning is not applicable to adding member functions to classes using Function.prototype like this:
function Foo(){} function bar(){} var foo = new Foo(); Foo.prototype.bar = bar; console.log(foo.__proto__.bar == bar); // true
In this example, both foo.__proto__.bar = bar and Foo.prototype.bar = bar achieve the same result without performance implications.
The issue arises when reassignment occurs to the __proto__ property itself:
function Employee() {} var fred = new Employee(); fred.__proto__ = Object.prototype; // Or equally: Object.setPrototypeOf(fred, Object.prototype);
The warning in the documentation explicitly states that modifying the prototype chain of an existing object disrupts optimizations performed by modern JavaScript engines. It suggests creating new objects with the desired prototype chain using Object.create().
This performance degradation stems from the internal implementation details of hidden classes in JavaScript engines like V8. When the prototype chain of an object is altered, its internal type changes, invalidating property lookup optimizations and compiled code.
Experts in the JavaScript community have highlighted the complexities and bug risks associated with allowing prototype mutation after creation, citing its adverse effects on type inference, proxies, and performance stability.
Therefore, while modifying member functions using Function.prototype does not pose performance concerns, reassigning the __proto__ property of an object should be avoided to prevent optimization penalties.
The above is the detailed content of Why Does Modifying an Object\'s [[Prototype]] Impact Performance?. For more information, please follow other related articles on the PHP Chinese website!