3 ms·
Please, please don't spread this "object factory" pattern any further than it's already gone. It's an incredibly inefficient way to do OOP in JavaScript. Every
by jashkenas 16y ago
Please, please don't spread this "object factory" pattern any further than it's already gone. It's an incredibly inefficient way to do OOP in JavaScript.
Every time you create a new instance of a Developer, you redefine every single function. This makes instantiation far slower than it would be if you used prototypes, and leaks memory like crazy: N Developers means N copies of each function.
So, first, it's slow -- take this test: https://gist.github.com/459112 https://gist.github.com/459112
Webkit: http://tinyurl.com/2csgzez http://tinyurl.com/2csgzez
Firefox: http://tinyurl.com/29wd2ms http://tinyurl.com/29wd2ms
And second, the memory use. Take a moderately-sized class, with ten member functions. The last time I benchmarked it in Chrome, using real prototypes, it takes a little under 32 megabytes of RAM to create a million instances of it. Try to create a million instances using the pattern you have above, and it spins the browser for minutes, and eats up 368 megabytes of RAM. IE just crashes.
If you're doing OOP in JS -- please use prototypes as Eich intended...
- bni 16y agoThanks for the benchmarks, I know the tradeoff for using this pattern. Im aware of that the function is defined in each object, and that it takes up memory. I dont agree that the memory is leaked, it is reclaimed when the object is deleted. As I never create millions of instances of objects, and this patterns dont seem to have a measurable impact on the rendering loop in my project, Ill just continue using it for now. I would call the pattern you propose to be the "object factory" pattern. And I am curious how to do classical inheritance and encapsulated vars with it.