elju
elju

Reputation: 435

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?

Upvotes: 10

Views: 1503

Answers (3)

Bergi
Bergi

Reputation: 664548

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.

Upvotes: 3

antichris
antichris

Reputation: 3157

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.

Upvotes: 5

Joe Simmons
Joe Simmons

Reputation: 1848

It all depends. Don't worry about it unless it's a big issue in the future.

Upvotes: -3

Related Questions