简体   繁体   English

在类上有很多方法会增加该类对象的开销吗?

[英]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(){
...
}

}

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. 现在,如果只有2种方法(如上所述)或100种方法(可能其中一些非常大),使用它的性能会发生什么变化。

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. 这适用于c#/ java类型语言,但对所有语言都知道。

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. 因此,除非您有其他设计理由,否则不应创建“仅数据”类。

That being said, there are other best-practices reasons why you might not want a class with a multitude of methods (eg the God object anti-pattern ). 话虽如此,还有其他最佳实践的原因,为什么你可能不想要一个有多种方法的类(例如上帝对象反模式 )。

No. In the CLR objects have a pointer to that type's meta information which includes everything necessary for reflection and the method table. 在CLR中,对象具有指向该类型的元信息的指针,该元信息包括反射和方法表所需的所有内容。 The overhead for looking up a method implementation in the method table is the same regardless of the number of entries in the table. 无论表中的条目数是多少,在方法表中查找方法实现的开销都是相同的。 See this article for more information. 有关更多信息,请参阅此文章 In a nutshell all objects have 8 bytes of overhead (4 for the type handle and 4 for the syncblock). 简而言之,所有对象都有8个字节的开销(4个用于类型句柄,4个用于syncblock)。

However, what might be slower is reflection. 然而,反思可能更慢。 It only makes since that if you want to enumerate through a type's metadata then it will be slower if there are more members declared in that type. 它只是因为如果你想枚举类型的元数据,那么如果在该类型中声明了更多的成员,它将会更慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM