Reputation: 5706
I want to know the overhead of JavaScript closures. Suppose I have the following function:
function sum(arr, sumMethod) {
var totalSize = 0;
for (index = 0; index < arr.length; ++index) {
totalSize += sumMethod(arr[index]);
}
return totalSize;
}
If I want to know the total size of all my transfers, then I could use a global accessor function to obtain the size of a transfer. This function is passed to sum
:
// Use a "global" method that is initialize only once
function getTransferSize(transfer) { return transfer.size };
...
// Obtain the total size of all transfers (called pretty often)
var totalTransferSize = sum(transfers, getTransferSize);
Another approach is to inline the accessor like this:
// Obtain the total size of all transfers (called pretty often)
var totalTransferSize = sum(transfers, function (transfer) { return transfer.size });
I would think the closure is only "compiled" once and reused over and over again, so the actual execution performance would be equal. A collegue of mine thinks that the closure is created over and over again and it hurts performance.
Can anyone explain what is the preferred method?
REMARK: I am actually using CoffeeScript, which makes closures much more readable. In CoffeeScript the code would look like this:
totalTransferSize = sum transfers, (t) -> t.size
I find this much more readable then using a global accessor function, so I would prefer to inline the accessor.
Upvotes: 1
Views: 612
Reputation: 665574
A collegue of mine thinks that the closure is created over and over again
Yes. Every time the function expression is evaluated, a new function object is instantiated.
and it hurts performance.
Unlikely. If you'd really care, measure it. The instantiation is probably much cheaper than the loop with the calls.
I would think the closure is only "compiled" once and reused over and over again
Yes, the code is compiled only once and shared by all the function instances.
so the actual execution performance would be equal.
Of the single call, yes.
Upvotes: 2