简体   繁体   English

闭包中的变量性能与函数参数的关系

[英]Performance of Variables in a Closure versus as Function Arguments

Does any one know about optimization effects of passing in a variable via function arguments versus having the variable available via a closure? 有没有人知道通过函数参数传递变量的优化效果与通过闭包获得变量? It seems like passing in variables via function arguments would be faster since objects are copied by reference (so fast copy time) and climbing the scope environments of the function requires checking the environment at each level. 似乎通过函数参数传递变量会更快,因为对象是通过引用复制的(如此快速的复制时间),并且爬上函数的范围环境需要检查每个级别的环境。 Here's the gist of what I mean 这是我的意思的要点

a = 5;
b = function() {
  alert(a);
}
b();

versus

a = 5;
b = function(c) {
  alert(c);
}
b(a);

Which in theory performs faster? 哪个在理论上表现得更快?

I had the same question a little while ago, so I slapped together a quick'n'dirty benchmark . 我不久前有同样的问题,所以我把一个快速的基准了一顿 It appears that most popular browsers (surprisingly) prefer looking up in the scope (FF24 very much so). 似乎大多数流行的浏览器(令人惊讶地)更喜欢在范围内查找(FF24非常如此)。

I hope this answers your question. 我希望这回答了你的问题。

climbing the scope environments of the function requires checking the environment at each level 攀登功能的范围环境需要检查每个级别的环境

Only theoretically. 只是在理论上。 In fact, since the scope chain is not dynamic, this can and will be optimized to a static reference. 实际上,由于范围链不是动态的,因此可以并且将优化为静态引用。

passing in variables via function arguments would be faster since objects are copied by reference (so fast copy time) 通过函数参数传入变量会更快,因为对象是通过引用复制的(因此复制时间很快)

Even it is very fast, they still need to be copied. 即使它非常快,它们仍然需要被复制。 The function needs to allocate extra memory for them, while the reference to the closure does not anything like that. 该函数需要为它们分配额外的内存,而对闭包的引用并不是那样的。


If you can put a value in the closure scope, do it. 如果您可以在闭包范围中放置一个值,请执行此操作。 It's only practical, you want to build a closure. 它只是实用的,你想建立一个闭包。 If you don't want and need variable arguments in your function, use parameters. 如果您不希望并且在函数中需要变量参数,请使用参数。 Use the more readable alternative. 使用更易读的替代方案。

It all depends. 这完全取决于。 Don't worry about it unless it's a big issue in the future. 不要担心它,除非它是未来的一个大问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM