4 ms·
Classes generally point you towards writing more performant code. Factory functions allow you to achieve the same performance, you just have to be a bit more ca
by unchar1 2y ago
Classes generally point you towards writing more performant code. Factory functions allow you to achieve the same performance, you just have to be a bit more careful not to cause a depot :)
For example,
1. field declarations [1] make sure that the fields are always initialized in the same order. That way most of your functions end up monomorphic, instead of being polymorphic [2]
2. Method declarations are also (almost) free, since you only pay for them once, during class initialization.
You also get a few other niceties such as private properties. You can emulate private properties with closures in factory functions but V8 has a hard time optimizing, unfortunately.
---
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#class_body https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
[2]: https://www.builder.io/blog/monomorphic-javascript https://www.builder.io/blog/monomorphic-javascript
- zanethomas 2y agoThe difference in performance is negligible for all but the most demanding applications. In which case I would still use factory functions, but just be more careful.
- unchar1 2y agoI agree. But it's one reason why someone who is concerned about performance, may prefer classes by default.