XNA Creators Club Online
Page 1 of 1 (3 items)
Sort Posts: Previous Next

Semi-OT: C# object memory footprints?

Last post 10/16/2009 9:43 AM by Cygon4. 2 replies.
  • 10/16/2009 6:49 AM

    Semi-OT: C# object memory footprints?

    Let's assume we have a class that has many methods for performing many complex operations and many fields / properties. Call it "ComplexClass". Also consider "SimpleClass" which only has fields/properties, and "SimpleClassController", which has all the methods needed by "SimpleClass".

    What is more efficient in terms of memory footprint? A collection of "ComplexClass" objects, or a collection of "SimpleClass" and a single "SimpleClassController"
    I was pulled up in a code review today for this reason, with the justification that the memory footprint for a collection of "ComplexClass" would be much greater that having a collection "SimpleClass" with "SimpleClassController".

    In the old days I might have said somehting like "yes but wouldn't all the objects would share a common code segment but have separate data segments?". At 4:40pm, my brain just wouldn't work fast enough :D
  • 10/16/2009 7:01 AM In reply to

    Re: Semi-OT: C# object memory footprints?

    HadesSpaniel:
    I might have said somehting like "yes but wouldn't all the objects share a common code segment but have separate data segments?".

    That's what you should have said.

    If the number of Fields is the same in ComplexClass and SimpleClass, there no justification to use the second solution (which doesn't even follow OOP principles).
  • 10/16/2009 9:43 AM In reply to

    Re: Semi-OT: C# object memory footprints?

    Arbitrarily splitting a class like that would only result in disadvantages for you. For example, it would be a lot harder to handle inheritance and it would be harder to understand what's going on in your code. And as long as all your objects are classes, the object overhead would stay the same (4 bytes vtable + 4 bytes lock handle + fields if I remember right).

    If you had a huge number of simple objects where you don't need inheritance, for example in a particle system, it is useful to follow the flyweight pattern. Use a struct for the flyweights themselves (and design operations so they operate directly on the array and process entire ranges of flyweights per call). This reduces the number of references the garbage collector has to track and keeps the objects in contiguous memory.

    Apart from these typical cases where you need to manage mass data, there isn't much use for flyweights. Especially if the flyweights are classes, not structs.

    Check out my website and blog for some interesting articles and useful utility classes!
    Nuclex Framework: threaded particles, skinnable GUI, vector fonts, texture atlasses and lots more.
    WiX XNA Installer: Professional-looking MSI installer template for XNA games.
Page 1 of 1 (3 items) Previous Next