Hidden classes and equivalence between {} object vs. custom constructor (v8)

 ̄綄美尐妖づ 提交于 2019-12-12 19:05:04

问题


Given this article:

http://richardartoul.github.io/jekyll/update/2015/04/26/hidden-classes.html

If you create a constructor such as:

function Point(x,y) {
  this.x = x;
  this.y = y;
}

Then doing this:

var obj1 = new Point(1,2);
var obj2 = new Point(3,4);

obj1.a = 5;
obj1.b = 10;

obj2.b = 10;
obj2.a = 5;

means you get some sort of performance optimizations under the hood.

I'm wondering though, if you just do this instead:

var obj1 = { a: 5, b: 10 }
var obj2 = { b: 10, a: 5 }

Will you get the same performance optimizations if you follow that pattern for thousands of objects, or is a new hidden class created for each var objn instance.

Basically wondering if it's required to use a constructor function to get this performance optimization.


回答1:


As the article says in its summary:

Always instantiate your object properties in the same order so that hidden classes, and subsequently optimized code, can be shared.

In your alternative example var obj1 = { a: 5, b: 10 }; var obj2 = { b: 10, a: 5 }, the properties are clearly not added in the same order, so the hidden classes cannot be shared.

You don't have to use a constructor per se, but using a constructor is the easiest way to ensure that you're getting the performance you want. (It is also generally considered ergonomic and good coding practice.)



来源:https://stackoverflow.com/questions/48916642/hidden-classes-and-equivalence-between-object-vs-custom-constructor-v8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!