Tell us what’s happening:
Hello,
Is there any performance advantage to use Class instead of the ES5 constructor standard in such case? It seems that there’s one more line of code in the ES6 Class constructor compared to the ES5 constructor.
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36
.
Challenge: Use class Syntax to Define a Constructor Function
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function
It’s almost exactly the same (class
is basically just syntactic sugar), but the class
version is a bit more explicit and gives more protection against screwing up (if you call it without new
you get an error). Among other things, you can also extend builtins (class MyArray extends Array
), which was impossible in some cases before class
Performance should be exactly the same, and it’s generally (YMMV, but normally definitely if you’re coming from another language) easier to understand what’s happening, clearer. Also, re amount of code, your example is slightly misleading because you have no methods
1 Like
Referencing those more knowledgeable than myself, specifically Eric Elliott. The tldr is that the performance advantages are irrelevant for many use cases, and they aren’t limited to the class
syntax. The entire article is on Medium here
class
syntax is a little nicer than the equivalent syntax for ES5 constructor functions, but the primary purpose is to hook up the delegate prototype chain, and good use-cases for delegate prototypes are rare. It really boils down to performance.
class
offers two kinds of performance optimizations: shared memory for properties stored on the delegate prototype, and property lookup optimizations.
…
Any type of closure scope or property access is measured in hundreds of thousands or millions of ops/second, so performance differences are rarely measurable in the context of an application, let alone impactful.
There are exceptions, of course. RxJS used class
instances because they’re faster than closure scopes, but RxJS is a general purpose utility library that might be used in the context of hundreds of thousands operations that need to be squeezed into a 16ms render loop.
ThreeJS uses classes, but ThreeJS is a 3d rendering library which might be used for game engines manipulating thousands of objects every 16ms.
It makes sense for libraries like ThreeJS and RxJS to go to extremes optimizing wherever they can.
1 Like