|
|
|
|
|
by GeneralMayhem
4699 days ago
|
|
This article does two things that are very dangerous, and never mentions the reasons why they're dangerous. * Messing with Function's prototype is very strongly frowned upon. It's tantamount to setting global variables. At the very least, give that definition an if (!Function.new) guard to prevent redefining another implementation that another script (or the browser!) has already given. * Adding methods in the constructor is awful even if you're not using inheritance, because it burns memory like crazy. If you define sayHi on Person.prototype, then every Person gets a reference to the same sayHi method. If you define this.sayHi in the constructor, then each Person you create gets its own copy of the function, making every Person heavier in memory. Not a big deal for a simple console.log, but if you have more complicated objects with a few dozen methods that you're using a bunch of you can really make things chug. |
|
- Map pointer: 8
- Properties pointer: 8
- Elements pointer: 8
- Code entry pointer: 8
- Initial Map/prototype pointer: 8
- SharedFunctionInfo pointer: 8
- Context pointer: 8
- Literals/Bindings pointer: 8
- Weak fields pointer: 8
So if you have a Person class with 30 methods, the methods are taking 30 * 72 = 2160 bytes at the very least. The actual data for a person might take 200 bytes, if we store e.g. full name, age and address so in this case there is like 10x overhead. If you print the details of 200 people per page request and there are 100 people connecting to your server, you are wasting 200 * 100 * 2160 =~ 40 megabytes on memory on storing all these useless function objects at that moment. That is just crazy.
And in GC language it's never just memory, a GC will eat exponentinally more CPU time when the amount of memory you use reaches closer and closer to limits.