文字对象和函数构造函数
我在 http://jsperf.com/literal-obj-vs-function- 上进行了此测试obj 和 Literal 在 FF6、Opera 10、IE8 上胜出,但在 Chrome 13.0.782.112 上 Function 方法更快,所以哪个是有更好的使用方法吗?
var A = {
aa : function(){
var i, j=[];
var arr = ['Literal', 'Function'];
for (i = 0; i < arr.length; i++){
j[i] = arr[i];
}
return j[0];
}
};
var A1 = A;
var A2 = A1;
A1.foo = ' Test';
alert(A1.aa() + A2.foo);
//Function test
function B(){
this.bb = function(){
var i, j=[];
var arr = ['Literal', 'Function'];
for (i = 0; i < arr.length; i++){
j[i] = arr[i];
}
return j[1];
}
}
var B1 = new B();
var B2 = new B();
B.prototype.foo = ' Test';
alert(B1.bb() + B2.foo);
I took this test on http://jsperf.com/literal-obj-vs-function-obj and Literal wins on FF6, Opera 10, IE8, but the Function method faster on Chrome 13.0.782.112, so which one is a better method to use?
var A = {
aa : function(){
var i, j=[];
var arr = ['Literal', 'Function'];
for (i = 0; i < arr.length; i++){
j[i] = arr[i];
}
return j[0];
}
};
var A1 = A;
var A2 = A1;
A1.foo = ' Test';
alert(A1.aa() + A2.foo);
//Function test
function B(){
this.bb = function(){
var i, j=[];
var arr = ['Literal', 'Function'];
for (i = 0; i < arr.length; i++){
j[i] = arr[i];
}
return j[1];
}
}
var B1 = new B();
var B2 = new B();
B.prototype.foo = ' Test';
alert(B1.bb() + B2.foo);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
说实话,我发现最好的是混合:
To tell you the truth, the best that I have found is a mix:
无论你喜欢哪一个。速度永远不应该成为一个问题,除非它成为您的应用程序中的真正问题。在我看来,你所做的事情似乎是过早的优化,这是浪费时间。等到需要优化代码的时候,再优化需要返工的部分。这是微不足道的。
Whichever one you prefer. Speed should never be a concern unless it becomes a real problem in your app. What you're doing looks like premature optimization to me, which is a waste of time. Wait until you need to optimize your code, then optimize the parts that need to be reworked. This is trivial.
Chrome 使用名为
隐藏类
的优化,使其能够更快地访问对象成员。我敢打赌,只有当通过 new 构造对象时才会启用此优化,因此通过 new 构造的对象比未构造的对象具有更快的成员访问速度通过
new
。Chrome uses an optimisation called
hidden classes
that allows it to do faster access to object members.I would bet that this optimisation is enabled only when the object is constructed via
new
, and as a result an object constructed vianew
would have faster member access than an object not constructed vianew
.根据 wikipedia,Chrome 拥有大约 17% 的市场份额。所以使用文字。
well, chrome has around 17% of the market share according to wikipedia. So use literals.
我怀疑你是否会做足够密集的事情来使差异变得重要。
函数风格的构造函数为您提供了私有变量的选项,这很好。
I doubt you're going to do anything intensive enough for the difference to matter.
Function style constructors give you the option of private variables, which is nice.