静态成员有助于提高内存效率吗? [英] Do static members help memory efficiency?

查看:30
本文介绍了静态成员有助于提高内存效率吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我希望在内存敏感应用程序中的数千个实例中使用一个类,如果我将静态功能分解为静态成员是否有帮助?

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?

我正在使用 Java,但我想一些通用规则也适用于其他托管环境(例如 .NET).

I'm working in Java, but I imagine some general rules to apply in other managed environments (such as .NET), too.

推荐答案

静态方法和幕后非静态(实例)方法的唯一区别是一个额外的、隐藏的参数(this) 传递给实例方法,并且可以使用间接调度(如果是虚拟的)调用该实例方法.不占用额外的代码空间.

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.

我的回答侧重于方法,但仔细阅读后,我发现问题更多地与静态数据有关.是的,静态数据在某种意义上会节省内存,因为它只有一个副本.当然,数据是否应该是静态的更多的是数据的意义或用途的函数,而不是内存节省.

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.

如果您需要拥有大量对象并希望节省内存,您可能还需要调查是否使用 'Flyweight' 模式 适用.

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.

这篇关于静态成员有助于提高内存效率吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆