Do static members help memory efficiency?
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.
The decision shouldn't be made on the grounds of efficiency - it should be made on the grounds of correctness.
If your variable represents a distinct value for each instance, it should be an instance variable.
If your variable is a common value associated with the type rather than an individual instance of the type, it should be a static variable.
You're correct, however - if you have a static variable, you won't "pay" for that with every instance. That just adds an extra reason to make variables static where they don't represent part of the state of the object.
When you mention methods in your question, are you talking about local variables? You'll get a new set of local variables for every method call - including recursive calls. However, this doesn't create a new set of static or instance variables.
The simple answer is yes. Creating an instance everytime there are none equals recreating the entire object, static methods and variables generally consumes less memory depending on how they are used. Of course if you only need to create one instance throughout your entire program, there's no difference. And remember you can always pass instances along as references where you can't have static objects and you need to reuse them.
链接地址: http://www.djcxy.com/p/82874.html上一篇: 什么时候在java中为静态变量分配内存?
下一篇: 静态成员是否有助于记忆效率?