Home:ALL Converter>Performance of Variables in a Closure versus as Function Arguments

Performance of Variables in a Closure versus as Function Arguments

Ask Time:2013-09-09T14:05:35         Author:elju

Json Formatter

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?

Author:elju,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18692323/performance-of-variables-in-a-closure-versus-as-function-arguments
antichris :

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).\n\nI hope this answers your question.",
2013-10-02T09:14:45
Bergi :

\n climbing the scope environments of the function requires checking the environment at each level\n\n\nOnly theoretically. In fact, since the scope chain is not dynamic, this can and will be optimized to a static reference.\n\n\n passing in variables via function arguments would be faster since objects are copied by reference (so fast copy time)\n\n\nEven 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.\n\n\n\nIf 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.",
2013-10-02T12:24:32
yy