简体   繁体   中英

Regarding memory size, cleaning up objects

Consider an example as below

class B
{
   int x;
}

class A
{
     int a;
     int b;
     B b1 = new B();

     void testMethod()
     {
        for (int i = 1; i < 10; i++)
            b1 = new B();
     }
}

class MainClass //Will never close this application
{
    static void Main(object[] args)
    {
        A a1 = new A();
        a1.testMethod();
    }
}

In this above example am creating a new Class B object everytime in the loop. So here my question is when i assign a new object to b1, what will happen to the previous object will that be cleaned up or will it remain up memory.

If it is not cleaning up and increasing the memory, how to clean up?

Each time you create a new object of B

b1 = new B();

the original object stored in b1 becomes inaccessible. This means that it is eligible for garbage collection. This does not mean that it will be cleaned from memory immediately though!

Objects that are eligible for GC will be actually GC'ed at "some time in the future". We don't know and don't need to know what time exactly. Just trust the GC.

In other words, after you run your testMethod , 9 objects of B will be eligible for GC or has already been collected, while the tenth object will remain stored in the variable b1 .

Each time you do this: b1= new B(); , you are assigning to b1 a new reference to a new object ( b1 is not a ValueType ), so, the previous reference is now unused, thus, the Garbage Collector is going to dispose it.

Summarizing: is not increasing the memory, because it is a Managed Resource

Life of any value type and reference type is depend on access specifier used to defined it and scope of that functionality. Functionality can be any class, function or loop where you defined your object.

In your case you defined reference type B b1 = new B() with out any access specifier (default access specifier) so it will be considered as internal . variable defined with internal can not be accessible to outside world.

Scope of b1 is limited to for loop which you defined your code.

for (int i = 1; i < 10; i++)
            b1 = new B();

If you notice above two conditions, you will understand object b1 is disposed by garbage collector after each iteration of for loop .

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