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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With