Reputation: 2228
I am working with a Javascript library (openlayers) and am trying to optimize some of the classes to reduce the overall memory footprint. I've noticed that for some of the classes I have no need for a large portion of the methods of that class - they will never be called.
I was about to rewrite some of these classes, stripping out the methods I don't need, but before I do I'd like to figure out whether or not that will have any noticeable effect on the memory footprint if I was to instantiate say 10,000 objects from the stripped-down class. Obviously if I remove properties that will help but I'm not sure about methods.
Can anyone give an explanation of how methods are stored, how much memory they consume, and possibly recommend any good books or other resources where I can bone up on this type of knowledge?
EDIT: Thank you for clarifying the difference between defining the method within the constructor function vs. the prototype. It appears to be a mixed bag but for the sake of argument let's assume they're defined in the constructor function (where it appears they'll have the most impact).
Upvotes: 2
Views: 561
Reputation: 166021
I think it really depends on whether a copy of your methods is created in memory for every instance of the object. For example:
var MyObj = function(x) {
this.doStuff = function() {
//Do some stuff
};
this.someProperty = x;
};
//myInstance will have its own copy of the doStuff method
var myInstance = new MyObj(10);
In the above code, every instance of MyObj
will require a copy of doStuff
in memory. However, if the method was declared on the prototype
, it's a different story:
var MyObj = function(x) {
this.someProperty = x;
};
MyObj.prototype.doStuff = function() {
//Do some stuff
};
//myInstance can still access doStuff, but all instances share one copy
var myInstance = new MyObj(10);
This time, every instance of MyObj
has its own property someProperty
, but when you call the doStuff
method, its not found on the instance itself, so the prototype
is looked at instead, where it is found and executed.
However, if, as you say, there are methods that are not being called at all, I don't see any reason to keep them no matter where they are declared. Personally, I would get rid of them (unless they are likely to provide value in the future). But I don't know your code, so that's a decision you will have to make.
Upvotes: 4