I’m creating my own JavaScript Array-like object and I have methods that call closures. I was just wondering where was the most efficient place to define a closure.
For example, imagine I have a map function and a chop function:
MyObject.prototype = { map: function(fn) { ... applies fn to each element ... }; chop: function() { this.map( function(element) { ... chop off last character ... } )}; }
Is it more efficient to do this instead?
MyObject.prototype = { map: function(fn) { ... applies fn to each element ... }; __chop: function(element) { ... chop off last character ... } chop: function() { this.map(this.__chop) }; }
The second one is more efficient. This
will create a new function object on each call to
chop()with the respective runtime and memory overhead. As there won’t be any lingering references to the new object, it can be immediately gargage collected, but it’s still bad practice to create more objects than necessary.I’d suggest the following pattern: