我的问题涉及静态方法与实例方法的性能特征及其可伸缩性.假设在这种情况下,所有类定义都在一个程序集中,并且需要多个离散指针类型.
考虑:
public sealed class InstanceClass
{
public int DoOperation1(string input)
{
// Some operation.
}
public int DoOperation2(string input)
{
// Some operation.
}
// … more instance methods.
}
public static class StaticClass
{
public static int DoOperation1(string input)
{
// Some operation.
}
public static int DoOperation2(string input)
{
// Some operation.
}
// … more static methods.
}
Run Code Online (Sandbox Code Playgroud)
上述类表示辅助样式模式.
在实例类中,解析实例方法需要花费一些时间来与StaticClass相反.
我的问题是:
保持状态不是问题(不需要字段或属性),使用静态类总是更好吗?
如果有相当多的静态类定义(例如100,每个都有许多静态方法),与相同数量的实例类定义相比,这会对执行性能或内存消耗产生负面影响吗?
当调用同一实例类中的另一个方法时,实例解析是否仍然发生?例如,使用[this]关键字,例如this.DoOperation2("abc")来自DoOperation1同一实例.
如果我有一个类,我期望在一个对内存敏感的应用程序中的数千个实例中使用它,如果我将静态功能分解为静态成员会有帮助吗?
我想静态方法和变量每个类存储一次,而对于非静态成员,必须为每个实例存储一些东西.
使用成员变量,似乎很清楚,但是为方法存储了哪种数据?
我正在使用Java,但我想象一些适用于其他托管环境(例如.NET)的通用规则.