简体   繁体   中英

C#.Net Casting and Instantiating Memory Allocation

Can some one explain me what is the different between this type of usage as performance vice. These are simply function callings on two inherited classes. First one uses the advantage of inheritance and second one discard it.

class ClassA 
{
    public void X()
    {
        Console.WriteLine("ClassA: X()");
    }
}

class ClassB : ClassA
{
    new public void X()
    {
        Console.WriteLine("ClassB: X()");
    }
}

class CheckMemory
{
    public void testMemory ()
    {  
        //Code block 1
        ClassB bob1 = new ClassB();
        ClassA aob1 = bob1;

        aob1.X();
        bob1.X();

        //Code block 2 
        ClassB bob2 = new ClassB();
        ClassA aob2 = new ClassA();

        aob2.X();
        bob2.X();
    }

}

In the first case instead of allocating a new Object we are reusing it ie both bob1 and aob1 are pointing to the same instance of an object on the Heap.

Where as in the second block you are creating two different instance of two different classes they occupy two memory locations in the heap , instead of the first one.

So the first one is memory efficient then the first , I hope this explanation helps.

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