Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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/Refe...

[2]: https://www.builder.io/blog/monomorphic-javascript



The 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.


I agree. But it's one reason why someone who is concerned about performance, may prefer classes by default.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: