#929 – Visualizing How Objects Are Removed from the Managed Heap
September 12, 2013 1 Comment
Suppose that you create two Dog objects as follows. (The BestFriend property refers to another dog that is the first dog’s best friend).
Dog myDog = new Dog("Kirby", 15); myDog.BestFriend = new Dog("Jack", 17);
The managed heap now looks as follows:
Now suppose that you then execute the following lines of code:
Dog yourDog = new Dog("Bowser", 3); yourDog = new Dog("Hank", 5);
Now the managed heap looks as follows:
At this point, let’s assume that the Garbage Collector runs, in an effort to reclaim some memory. Notice that the Bowser object is no longer referenced by any reference-typed variable or by another object. Bowser gets marked for collection:
All objects not marked for collection are compacted, moving them to the front (left) of the heap. After the Garbage Collector runs, the heap is as shown below. Note that the memory for the Bowser object is reclaimed by the heap.