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

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

问题描述

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

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天全站免登陆