问题
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);
回答1:
To tell you the truth, the best that I have found is a mix:
function C() {
var i, j = [],
foo;
return {
bb: function() {
var arr = ['Literal', 'Function'];
for (i = 0; i < arr.length; i++) {
j[i] = arr[i];
}
return j[1];
},
setFoo: function(val) {
foo = val;
},
getFoo: function() {
return foo;
}
}
}
var C1 = C();
var C2 = C();
C2.setFoo(' Test');
console.log(C1.bb(), C2.getFoo());
回答2:
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.
回答3:
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 via new
would have faster member access than an object not constructed via new
.
回答4:
well, chrome has around 17% of the market share according to wikipedia. So use literals.
回答5:
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.
来源:https://stackoverflow.com/questions/7152005/literal-object-and-function-constructor