Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 517
elju Avatar asked Sep 09 '13 06:09

elju


2 Answers

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).

I hope this answers your question.

like image 116
antichris Avatar answered Oct 11 '22 06:10

antichris


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.

like image 3
Bergi Avatar answered Oct 11 '22 07:10

Bergi