5 ms·
In both examples, the function is only allocated once, no matter how it's instantiated. Where you have to be careful is if you have a function that's being cal
by isntitvacant 14y ago
In both examples, the function is only allocated once, no matter how it's instantiated.
Where you have to be careful is if you have a function that's being called repeatedly and it contains a function instantiation -- that function will be reallocated each time.
[1,2,3].forEach(function(x) {
return (function(a, b) { return a * b })(x, 2)
})
Will repeatedly allocate that inner multiplication function, vs:
mul = function(a, b) { return a * b }
;[1,2,3].forEach(function(x) {
return mul(x, 2)
})
Will only allocate that multiplication function once.
- cmwelsh 14y agoI think we are in complete agreement. Your example is a little prettier however you still have this "unoptimized" line: ;[1,2,3].forEach(function(x) { If this line is executed more than once, the nested function will be created again and again, wasting memory. However, some people may see my advice here as a micro-optimization. Thus, don't make your code ugly until you identify the real-world bottlenecks. I have updated my code in the grand-parent comment to explain myself a little more clearly (maybe)...