{} 对象与自定义构造函数之间的隐藏类和等效性 (v8) [英] Hidden classes and equivalence between {} object vs. custom constructor (v8)
问题描述
鉴于这篇文章:
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;
}
然后这样做:
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 }
如果您对数千个对象遵循该模式,或者为每个 var objn
实例创建一个新的隐藏类,您是否会获得相同的性能优化.
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.
推荐答案
正如文章在其摘要中所说:
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.
在您的替代示例中 var obj1 = { a: 5, b: 10 };var obj2 = { b: 10, a: 5 }
,属性显然不是按照相同的顺序添加的,所以隐藏的类无法共享.
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.)
这篇关于{} 对象与自定义构造函数之间的隐藏类和等效性 (v8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!