Re:Writing Fast, Memory-Efficient JavaScript
by cmwelsh on Monday November 05, 2012 @02:13PM
(#4745271)
Avoiding nested anonymous functions is good for more reasons than listed in the article. The article lists closures holding references to the closed-over variables as being a source of wasted memory. Another point is the fact that anonymous variables require memory allocation each time they are created:
The function will be created every time the outer forEach loop is called.
Save your created functions for later to save memory.
[ Parent
| on HN ]
Re:Writing Fast, Memory-Efficient JavaScript
by isntitvacant on Monday November 05, 2012 @02:30PM
(#4745353)
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.
Re:Writing Fast, Memory-Efficient JavaScript
by cmwelsh on Monday November 05, 2012 @04:05PM
(#4745790)
I 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)...