2 ms·
Creating an object and creating a closure both need to allocate memory in the VM, but the closure doesn't need to expose its internals the way an object does an
by jeremiep 11y ago
Creating an object and creating a closure both need to allocate memory in the VM, but the closure doesn't need to expose its internals the way an object does and therefore can be further optimized by the runtime.
If you need to write performance critical JavaScript, then allocating new objects will be just as slow as creating new closures. In either cases you should allocate them ahead of time and then closures are still the clear winner.
- deleted 11y ago[deleted]
- warfangle 11y ago> Creating an object and creating a closure both need to allocate memory in the VM, but the closure doesn't need to expose its internals the way an object does and therefore can be further optimized by the runtime. Actually... creating an object instance via a constructor lets the runtime use an internal class, which improves performance (as long as you don't modify its properties post-construction). This is a well-known aspect of V8 performance.
- jeremiep 11y agoEven with an internal class you're still doing lookups for properties. A closure can instead use local variables which are accessed by index. Why do you think its good practice to pull properties out of objects and into local variables before a tight loop?
- Touche 11y ago> If you need to write performance critical JavaScript, then allocating new objects will be just as slow as creating new closures. No, it won't. This code: function createThing() { return { doSomething: function(){} }; } Performs much worse (at scale) than this code: new Thing(); And it consumes a lot more memory since Thing.prototype.doSomething is 1 function in memory and the former is N functions.
- jeremiep 11y agoI try to avoid OOP in my JavaScript code like the plague, I'd probably write it like this: function doSomething(obj){} var objs = [{},{},{}]; objs.forEach(doSomething); If I need late binding I'll use something like clojure's multi-methods. Both closures and prototypes aren't needed for this :)