30 ms·
" Usage of class is not bad. It definitely has its place. If you have some really “hot” code that’s a bottleneck for your application, then using class can real
by ES2048 9y ago
"
Usage of class is not bad. It definitely has its place. If you have some really “hot” code that’s a bottleneck for your application, then using class can really speed things up. But 99% of the time, that’s not the case. And I don’t see how classes and the added complexity of this is worth it for most cases (let’s not even get started with prototypal inheritance). I have yet to have a situation where I needed classes for performance. So I only use them for React components because that’s what you have to do if you need to use state/lifecycle methods (but maybe not in the future).
"
Why would classes have any inherent performance benefits (and over what) ?
- rhinoceraptor 9y agoSince classes are just sugar over prototypes, their performance is just about the same for instantiation. I assume the article is comparing them to functions that return an object literal with methods. Here is a simple example of equivalent code in a class, function with a closure, and a prototype: class FooClass { constructor (bar) { this.bar = bar; } getBar () { return this.bar; } setBar (bar) { this.bar = bar; } } function FooClosure (bar) { var _bar = bar; return { getBar () { return _bar; }, setBar (bar) { _bar = bar; } }; } function FooPrototype (bar) { this.bar = bar; } FooPrototype.prototype.getBar = function () { return this.bar; }; FooPrototype.prototype.setBar = function (bar) { this.bar = bar; }; When instantiating a lot of objects, the prototype and class are practically the same, but the function closure pattern is a lot slower. On my machine, instantiating one hundred million of the class or prototype each took about 500ms, but the closure function took about 3s.