是否有很多在一个类的方法增加该类的对象的开销? [英] Does having lots of methods on a class increase the overhead of that class's object?
问题描述
想象一下,我使用一个类来从数据库中带回的物品,比如
Imagine I am using a class to bring back items from a database, say
class BankRecord {
public int id;
public int balance;
public void GetOverdraft() {
...
}
public void MakeBankrupt(){
...
}
}
现在,会发生什么样使用这个是否有表现仅仅2种方法(如上)或100的方法,也许他们中的一些非常大的。
Now, what would happen to the performance of using this if there were just 2 methods (as above) or 100 methods, maybe some of them very large.
会实例化数以百计的这些对象的更糟糕,如果所有的方法是每个对象?这是C#/ Java类型语言,但它是很好的了解所有的语言。
Would instancing hundreds of these objects be worse if all the methods were on each object? This is for c#/java type languages, but it would be good to know for all languages.
或者是很好的做法,有一个单独的类,执行所有对这些对象的行为,并保留对象作为纯数据类?
Or is it good practice to have a seperate class, to perform all the actions on these objects, and leave the object as a pure data class?
推荐答案
创建时,运行时不会重复代码一个对象的实例。只有创建实例时的成员字段在内存中分配的空间。出于这个原因,你不应该,除非你有其他的一些设计这样做的理由打造仅数据类。
The runtime does not duplicate the code when creating an instance of a object. Only the member fields are allocated space in memory when an instance is created. For this reason, you shouldn't be creating "data-only" classes unless you have some other design reason for doing so.
话虽这么说,还有其他的最好-practices原因,您可能不希望一类的方法众多(如上帝反对反模式)。
That being said, there are other best-practices reasons why you might not want a class with a multitude of methods (e.g. the God object anti-pattern).
这篇关于是否有很多在一个类的方法增加该类的对象的开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!