I would like to ask for clarification on how .net Garbage Collector works in this case.
I have a static function in which I allocate the byte array over and over again. I am inserting byte array reference into the list. The reference to the byte array or the list is not passed outside this function.
public static void StressMem(TimeSpan duration)
{
var bgnTm = DateTime.Now;
var data = new List<byte[]>();
while (true)
{
var arr = new byte[1024];
data.Add(arr);
var difTm = DateTime.Now - bgnTm;
if (difTm > duration) break;
}
}
I was expecting the memory to be freed (after some time) when this function was finished. But this is not happening to me. Why is this happening?
dotnet 5.0.302
The GC is in principle free to run whenever it wants, or never at all for that matter. In practice I would not expect it to run unless you are actually trying to allocating something. So after StressMem
returns you might not see any GC unless you do some more work that require memory. If you ran StressMem
in a loop I would expect frequent GCs.
Note that that does not necessarily mean that the memory usage for the process will decrease. The garbage collector may return memory to the OS if physical memory runs low, but is you have free memory, why not use it?
If you are investigating how your application uses memory I would recommend a memory and/or performance profiler. They should reveal how much time you are using for GC, what you are using memory for, how much you are allocating etc.