考虑以下我返回值的函数。
方法一:
function getData() {
var myData = '';
var DateObj = new Date();
for (i=0; i<50000; i++) {
myData += "'" + DateObj.toString() +"', ";
}
return myData;
}
方法二:
function getData(calbck) {
try{
var myData = '';
var DateObj = new Date();
for (i=0; i<50000; i++) {
myData += "'" + DateObj.toString() +"', ";
}
} catch(e){
return calbck(e,null);
}
return calbck(null, myData);
}
我已经测试了这两种方法。选择哪一个最好?
谢谢
更新:使用以下代码进行测试。
function getData1() {
var myData = '';
var DateObj = new Date();
for (i=0; i<50000; i++) {
myData += "'" + DateObj.toString() +"', ";
}
return myData;
}
function getData2(calbck) {
try{
var myData = '';
var DateObj = new Date();
for (i=0; i<50000; i++) {
myData += "'" + DateObj.toString() +"', ";
}
} catch(e){
return calbck(e,null);
}
return calbck(null, myData);
}
console.log('call getData1() start');
console.time('5000000-getData1()');
getData1()
console.log('call getData1() End');
console.timeEnd('5000000-getData1()');
console.log('call getData2(calbck) start');
console.time('5000000-getData2(calbck)');
getData2(function(err,Returned_value){
if(err) return console.log(err);
//console.log(Returned_value);
console.log('call getData2(calbck) End');
console.timeEnd('5000000-getData2(calbck)');
});
输出:
D:\Test>node app.js
call getData1() start
call getData1() End
5000000-getData1(): 91ms
call getData2(calbck) start
call getData2(calbck) End
5000000-getData2(calbck): 76ms
D:\Test>node app.js
call getData1() start
call getData1() End
5000000-getData1(): 111ms
call getData2(calbck) start
call getData2(calbck) End
5000000-getData2(calbck): 78ms