Question

    static void Main(string[] args)
    {
        var c2 = new Class2();
        var c3 = new Class3();
        var c1 = new Class1(c2, c3);
        c1.Method1();
    }

    class Class1
    {
        readonly Class2 _class2;
        readonly Class3 _class3;
        public Class1(Class2 class2, Class3 class3)
        {
            _class2 = class2;
            _class3 = class3;
        }
        public void Method1() {
            _class2.PerformM1();
            _class3.PerformM2();
        }
    }
    class Class2
    {
        public void PerformM1()
        {
            //do some operation
        }
    }
    class Class3
    {
        public void PerformM2()
        {
            //do some operation
        }
    }

Question based on above code:

  1. How much memory does object of Class1 has when it is created?
  2. Does any memory increases or decreases when I perform c1.Method1(); keeping in mind that none of the classes have any global fields that might acquire any space.

Edit

Expanding with one more question:

  1. If creating new objects of Class1 and calling methods of c1 object does not involve much memory usage, then is it correct to say that I don't need a lock in the above provided sample code.

I can simply create n number of objects and assign individual object to individual Task( or thread)?

Was it helpful?

Solution

  1. The (possibly slightly outdated) article Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects explains that in .Net, each object takes at least 8 bytes (4 bytes for syncblock, 4 bytes for TypeHandle). Class1 has two instance fields, both of which are references. Assuming your code is running as a 32-bit application, that means 4 more bytes for each reference. That would mean each instance of Class1 takes 16 bytes in total.

    Though this makes me confused about your title, because Class1 does have some state.

  2. The only memory required directly by the call to Method1() is some stack space for the activation frame of the call. It won't allocate any memory from the heap.

Though in the end, it's most likely that all of this won't matter to you.


is it correct to say that I don't need a lock in the above provided sample code.

That's hard to say without actually seeing your code. But in general, creating one instance of a class for each task is a valid approach. And that includes types that do have some state (assuming it's not shared state).

OTHER TIPS

  1. You can use GC.GetTotalmemory(false) method to measure the current memory usage.
  2. You can also use some kind of memory profilers like red gate ANTS memory profiler

  3. Memory consumption should not increase when c1.Method1(); is performed, given C2,C3 do not have any objects initialized or refer to other classes which has objects initialized.

Licensed under: CC-BY-SA with attribution
scroll top