假设对于时间要求严格的应用程序,使用函数声明或函数表达式而不是大量执行的回调中的内联函数总是更好的假设是否安全?
考虑以下测试程序:
var x;
var count3 = function count3() {
x++;
}
var count2 = function () {
x++;
}
function count() {
x++;
}
function execute(cb) {
cb();
}
x = 0;
var a = new Date().getTime();
for (var i = 0; i < 100000000; i++) {
execute(function named() {
x++;
})
}
a = new Date().getTime() - a;
console.log("Named inline function: " + a);
x = 0;
a = new Date().getTime();
for (var i = 0; i < 100000000; i++) {
execute(function () {
x++;
})
}
a = new Date().getTime() - a;
console.log("Anonymous inline function: " + a);
x = 0;
a = new Date().getTime();
for (var i = 0; i < 100000000; i++) {
execute(count);
}
a = new Date().getTime() - a;
console.log("Function declaration: " + a);
x = 0;
a = new Date().getTime();
for (var i = 0; i < 100000000; i++) {
execute(count2);
}
a = new Date().getTime() - a;
console.log("Anonymous function expression:" + a);
x = 0;
a = new Date().getTime();
for (var i = 0; i < 100000000; i++) {
execute(count3);
}
a = new Date().getTime() - a;
console.log("Named function expression:" + a);
这给出了以下输出(以毫秒为单位):
Named inline function: 2347
Anonymous inline function: 2121
Function declaration: 771
Anonymous function expression:750
Named function expression:752
在我简陋的笔记本电脑上,函数声明和函数表达式比内联函数快 3 倍。