I read that adding functions to an object will chew up more memory then adding functions to the prototype of the object.
function Obj() {
this.M = function() { // do something };
}
var o = new Obj();
The idea was that for every construction of Obj, a new function is created and applied to Obj, thus increasing memory use. For 1000 instances of Obj, 1000 functions will need to be created.
function Obj() {
}
Obj.prototype.M = function() { // do something };
var o = new Obj();
For 1000 instances of Obj, in this case, only the one function is created. Netting a total saving of 999 * sizeof(M) memory.
Is this really the case? If it is, in what category would the following fall under:
function Obj() {
Obj.prototype.M = function() { // do something };
}
var o = new Obj();
My instincts tell me that for every construction of Obj in this example, the prototype will be assigned each time. I’m not sure what to think of memory use in this case, since assigning the same function to the prototype would just replace the function instead of creating N copies of it for N instances.
I have just started using this method to encapsulate creation of the member functions, but want to be sure that I’m not doing the wrong thing.
Well, as you surmised, that’ll create an anonymous function and assign it to the prototype during the construction of a new object. It’s just pointless, and slightly slower… unless you actually capture something like an argument to the constructor in that closure, in which case it’s also weird – because whatever the current
M()happens to be, it’ll still be shared with all instances of Obj:If you come up with a good use for this, I’d love to hear it…
See also: