'Difference between Garbage Collection and a For Loop destroying objetcs
I have this code that creates 5500 objetcs of a class and then it outputs the the total allocated bytes and total memory so that way I can see the changes in the allocated bytes. I also have a destructor so I can see approximately when the Garbage Collection occurs. From the output on the console, I can see that the GC does not occur after each iteration of the for loop and I heard from somewhere that a for loop constructs and destructs objects after each iteration(obviously if the loop creates objects in its body). Now I am wondering if the action of the for loop of constructing and destructing objects after each iteration is not Garbage Collection(It is not done by the process of Garbage Collection), then what is It? How does the for loop destruct the object, considering the Object is stored in the heap? How is the object removed from the heap, after each iteration?
class Destruct {
int x;
int g;
public Destruct(int i, int h) {
x = i;
g = h;
}
~Destruct() {
Console.WriteLine($"Destructor called for {x}");
}
public void Generator(int o,int l) {
new Destruct(o,l);
}
}
class one {
static void Main() {
int count = 1;
Destruct ob = new Destruct(0,0);
long tot;
long mem;
for (int i = 1, y=1; i <= 5500; i++,y++) {
ob.Generator(i,y);
tot = GC.GetTotalAllocatedBytes();
mem = GC.GetTotalMemory(false);
count++;
Console.WriteLine(count+" "+tot+" "+mem+" "+(tot-mem));
}
Console.WriteLine("Done");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
