简体   繁体   中英

C#: simple vs complex objects and memory usage

When dealing with large collections, which of the following approaches is better?

Class SimpleObject with only fields/properties and class SimpleObjectController that contains all the method implementations required by SimpleObject. At runtime, I build a collection of SimpleObjects, instantiate one SimpleObjectController and call it's methods, passing the SimpleObject I want to work with.

or

Class "ComplexObject" that aggregates the SimpleObject and SimpleObjectController in the traditional OO approach. At runtime I have a collection of ComplexObjects, iterate over them, calling their methods as needed.

It has been suggested to me that the first approach is preferable in terms of memory usage as all the heavyweight code is only in one object instead of each one in the collection. My understanding was that if we had 1000 of these objects in a collection, that doesn't mean there is 1000 of the same method implementations sitting in memory. There would be 1000 instances of the data, but they would share the one code instance (x86 code segment & data segment?). It also seems to fly in the face of general OO principles and encapsulation.

You should take the second approach. Code has no per-instance cost: there is one copy of the code for each class , not each instance. So there is no memory benefit to the first approach. And you're right, the OO style is to put the functions in with the data, in order to encapsulate them; if you took the first approach, somebody could easily mis-manipulate a SimpleObject by working with it directly instead of through the controller methods.

I don't imagine there would be any difference, besides having two class definitions instead of one.

You're correct in thinking that there isn't 1000 instances of the method implementations. Once compiled, all the methods become "global" methods that have a hidden ComplexObject argument that is mapped to the this keyword in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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