tags:

views:

109

answers:

2

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.

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?

+3  A: 

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 (e.g. the God object anti-pattern).

Joseph Sturtevant
+2  A: 

No. In the CLR objects have a pointer to that type's meta information which includes everything necessary for reflection and the method table. 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).

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.

Brian Gideon