本文介绍了为什么改变对象的[[prototype]]对性能有害?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自标准的 以及非标准:

From the MDN docs for the standard setPrototypeOf function as well as the non-standard __proto__ property:

使用 Function.prototype 添加属性 方式将成员函数添加到javascript类。然后如下所示:

Using Function.prototype to add properties is the way to add member functions to javascript classes. Then as the following shows:

function Foo(){}
function bar(){}

var foo = new Foo();

// This is bad:
//foo.__proto__.bar = bar;

// But this is okay
Foo.prototype.bar = bar;

// Both cause this to be true:
console.log(foo.__proto__.bar == bar); // true

为什么 foo .__ proto__.bar = bar; 不好?如果它的错误不是 Foo.prototype.bar = bar; 同样糟糕?

Why is foo.__proto__.bar = bar; bad? If its bad isn't Foo.prototype.bar = bar; just as bad?

然后为什么会出现这样的警告: 它很慢并且不可避免地减慢了现代JavaScript实现中的后续执行速度 。当然 Foo.prototype.bar = bar; 并不是那么糟糕。

Then why this warning: it is very slow and unavoidably slows down subsequent execution in modern JavaScript implementations. Surely Foo.prototype.bar = bar; is not that bad.

更新也许通过突变他们意味着重新分配。见接受的答案。

Update Perhaps by mutation they meant reassignment. See accepted answer.

推荐答案

// This is bad:
//foo.__proto__.bar = bar;

// But this is okay
Foo.prototype.bar = bar;


否。两者都在做同样的事情(如 foo .__ proto__ === Foo.prototype ),两者都很好。他们只是在 Object.getPrototypeOf(foo)对象上创建一个 bar 属性。

No. Both are doing the same thing (as foo.__proto__ === Foo.prototype), and both are fine. They're just creating a bar property on the Object.getPrototypeOf(foo) object.

该陈述所指的是分配给 __ proto __ 属性本身:

What the statement refers to is assigning to the __proto__ property itself:

function Employee() {}
var fred = new Employee();

// Assign a new object to __proto__
fred.__proto__ = Object.prototype;
// Or equally:
Object.setPrototypeOf(fred, Object.prototype);

详细介绍:

The warning at the Object.prototype page goes into more detail:

他们只是声明更改已存在对象的原型链 杀死优化。相反,你应该通过 Object.create()创建一个具有不同原型链的新对象。

They simply state that changing the prototype chain of an already existing object kills optimisations. Instead, you're supposed to create a new object with a different prototype chain via Object.create().

我找不到明确的参考,但如果我们考虑如何已经实现,我们可以看到这里可能会发生什么。当更改对象的原型链时,其内部类型会发生变化 - 它不会像添加属性时那样简单地成为子类,而是完全交换。这意味着刷新所有属性查找优化,并且需要丢弃预编译代码。或者它只是回退到非优化代码。

I couldn't find an explicit reference, but if we consider how V8's hidden classes are implemented, we can see what might go on here. When changing the prototype chain of an object, its internal type changes - it does not simply become a subclass like when adding a property, but is completely swapped. It means that all property lookup optimisations are flushed, and precompiled code will need to be discarded. Or it simply falls back to non-optimized code.

一些值得注意的报价:







  • 这篇关于为什么改变对象的[[prototype]]对性能有害?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-06 18:25