by cmwelsh · 14y ago · 0 comments
// 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.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. ;[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)...