函数声明比函数表达式更快?

时间:2011-03-25 14:35:50

标签: javascript function performance

差异黑白功能声明&函数表达式在var functionName = function() {} vs function functionName() {}中有详细描述 在此提到函数声明在分析时评估,&函数表达式在执行阶段进行评估

bytes.com中提到函数声明比函数表达式快。

我为此创建了一个基本测试用例:http://jsperf.com/function-declaration-vs-function-expression

功能声明

function myfunc() {
 alert("yo");
}
myfunc();

功能表达

var myfunc = function() {
 alert("yo");
}
myfunc();

测试显示函数表达比函数声明慢<90%

为什么速度有这么大差异?

修改
来自http://jsperf.com/function-declaration-vs-function-expression

的结果

Chrome, IE9, Opera & Safari - &gt;功能声明比功能表达

更快

Firefox, IE7, IE8 - &gt;函数表达比函数声明

更快

IE9 中,功能声明更快,而在IE 7&amp; 8函数表达式更快。 是因为IE9中的JavaScript引擎发生了变化,还是故意这样做?

2 个答案:

答案 0 :(得分:2)

Firefox也有非标准Function Statements,这使得有条件地在功能声明之间进行选择(按规格,你不能)。只需使用example of Juriy "kangax" Zaytsev

if (true) {
    function foo(){ return 1; }
} else {
    function foo(){ return 2; }
}
foo(); // 1
// Note that other clients interpet `foo` as function declaration here, 
// overwriting first `foo` with the second one, and producing "2", not "1" as a result

所以那些是在执行时编译的,而不是在解析阶段:

  

在变量实例化期间不声明函数语句。它们在运行时声明,就像函数表达式一样。

其他浏览器可能会预编译函数声明,使它们在运行时执行得更快,但Firefox必须在运行时解释函数声明,导致基于Gecko的浏览器中函数声明和函数表达式的速度差别不大

答案 1 :(得分:1)

这必须是与浏览器相关的问题。有些浏览器可能会以不同的方式编译javascript,如果它是表达式而不是声明,有些浏览器可能会对它们完全相同。

相关问题