6 ms·
Composition over inheritance wins, so hard. (edit: downvote for a typically well-thought-of idiom, especially with regard to a language like js? .. if you disa
by warfangle 11y ago
Composition over inheritance wins, so hard.
(edit: downvote for a typically well-thought-of idiom, especially with regard to a language like js? .. if you disagree, why not talk about it?)
- Touche 11y agoClasses are unavoidable in JavaScript if you care about performance. Recreating redundant functions inside a closure in performance critical code is a sure way to have slow apps.
- jeremiep 11y agoCreating 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 :)
- warfangle 11y agoCertainly. But if object instantiation / garbage collection is your bottle neck, you should be using an object pool, anyways. You wouldn't put _every_ object in an object pool, though - only those which obviously impact performance after identifying them as a bottleneck. I'd hope you optimize for maintainability before you optimize for performance, otherwise you'll end up optimizing bottlenecks that don't exist.