4 ms·
Avoiding nested anonymous functions is good for more reasons than listed in the article. The article lists closures holding references to the closed-over variab
by cmwelsh 14y ago
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:
// Uses more memory:
Foo.prototype.someFunction = function () {
;[2, 5, 9].forEach(function (element, index, array) {
console.log("a[" + index + "] = " + element)
})
}
The function will be created every time the outer forEach loop is called.
// Uses less memory:
Foo.prototype.logArrayElements = function (element, index, array) {
console.log("a[" + index + "] = " + element)
}
Foo.prototype.someFunction = function () {
;[2, 5, 9].forEach(this.logArrayElements)
}
Save your created functions for later to save memory.
- btipling 14y agoWhy an expression and not simply `function logArrayElements`? If you do the latter you'll see more information if you wanted to introspect (toString on the function, or in an error traceback).
- cmwelsh 14y agoI adapted this from some game engine code. I have updated my example to show why I wasn't using a `function` statement. Thanks.
- isntitvacant 14y agoIn 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)...