从自执行函数返回函数的Javascript性能是什么?

rob*_*obC 11 javascript performance scope

在Firefox中,以下两个函数之间似乎存在很大的性能差异:

var n1 = 12;

var add1 = function(n2){
    return n1 + n2;
}

var add2 = (function(){
    return function(n2){
            return n1 + n2;
    }
})();
Run Code Online (Sandbox Code Playgroud)

我认为这必须归结于另一个范围的引入,因此创建了第三个示例,其中变量缓存了一个级别.但这显示出更大的减少(80%!)

var add3 = (function(){
    var cn1 = n1;
    return function(n2){
            return cn1 + n2;
    }
})();
Run Code Online (Sandbox Code Playgroud)

我本以为这里的关闭将缩小性能差距,而不是扩大它.有没有人知道这里发生了什么?

jsPerf测试页:http://jsperf.com/variable-scope-speed

J. *_*uni 0

var n1 = 12;

// "add1" is superfast in Firefox, but not in Chrome. Why?
// it seems Firefox is smarter in retrieving n1 value from global scope
var add1 = function(n2){
        return n1 + n2;
}

// "add2" is much slower in Firefox, but in Chrome the speed is almost equal to "add2"
// it seems that Firefox's smart retrieving from global scope is not applied in this case
// it is understandable that "add2" is slower, because the interpreter needs to go back two levels in the scope chain to find the "n1" variable value
var add2 = (function(){
        return function(n2){
                return n1 + n2;
        }
})();

// If JavaScript works as PHP, then it won't copy "n1" value in "cn1".
// If this is the case, then it is understandle why it is slower.
// The interpreter first needs to search and find "cn1" value;
// when it finally finds it in the previous scope level,
// then it needs to start a second "search and find travel", looking for the value.
// This means "cn1" does not contain "12", but a reference to it in the memory.
// While I don't know if this is how JavaScript engine works,
// I know that PHP does not create a copy of the value -
// both variables share the same content in the memory.
// Short story being: it is slower because it must perform two "searches" instead of one.
var add3 = (function(){
        var cn1 = n1;
        return function(n2){
                return cn1 + n2;
        }
})();
Run Code Online (Sandbox Code Playgroud)