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).
I think it really depends on whether a copy of your methods is created in memory for every instance of the object. For example:
In the above code, every instance of
MyObjwill require a copy ofdoStuffin memory. However, if the method was declared on theprototype, it’s a different story:This time, every instance of
MyObjhas its own propertysomeProperty, but when you call thedoStuffmethod, its not found on the instance itself, so theprototypeis 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.