由于jsperf关闭,我有一个非常简单的性能测试设置,以评估使用构造函数比使用工厂风格函数快多少。
不幸的是,我的结果表明使用OOP方法(构造函数版本)大约(至少)慢了10倍。
下面是我的两个测试:
function stdFactorial(num)
{
// If the number is less than 0, reject it.
if (num < 0) {
return -1;
}
// If the number is 0, its factorial is 1.
else if (num == 0) {
return 1;
}
var tmp = num;
while (num-- > 2) {
tmp *= num;
}
return tmp;
}
console.time("std factorial test");
for (var i = 1; i < 10000; i++) {
stdFactorial(20);
}
console.timeEnd("std factorial test");
这次是相同的函数,只是这次使用了'this'关键字
function oopFactorial(){
this.doCalc = function(num){
// If the number is less than 0, reject it.
if (num < 0) {
return -1;
}
// If the number is 0, its factorial is 1.
else if (num == 0) {
return 1;
}
var tmp = num;
while (num-- > 2) {
tmp *= num;
}
console.log('...')
return tmp;
}
};
var instance = new oopFactorial();
console.time("oop factorial test");
(function(){
for (var i = 1; i < 10000; i++) {
instance.doCalc(20);
}
})();
console.timeEnd("oop factorial test");
运行http://codepen.io/nicholasabrams/pen/MwVNNR和http://codepen.io/nicholasabrams/pen/bdvXPK,检查控制台。我做错了什么?
在doCalc方法中有一个console.log调用延迟执行。删除它,你会得到不同的结果