If I have a class that I expect to be used in thousands of instances in a memory-sensitive application, does it help if I factor out static functionality to static members?
I imagine that static methods and variables are stored once per class while for non-static members there has to be something stored for each instance.
With member variables, it seems quite clear, but what kind of data is stored for methods?
I’m working in Java, but I imagine some general rules to apply in other managed environments (such as .NET), too.
The only difference between static methods and non-static (instance) methods behind the scenes is that an extra, hidden parameter (
this) is passed to instance methods and that instance methods might be called using an indirect dispatch (if virtual). There is no additional code space taken.Edit:
My answer focused on methods, but on closer reading I see that the question is more about static data. Yes, static data will in a sense save memory since there’s only a single copy of it. Of course, whether or not data should be static is more a function of the meaning or use of the data, not memory savings.
If you need to have a large number of objects and want to conserve memory, you may want to also investigate if using the ‘Flyweight’ pattern is applicable.