Garbage collection in C# not carried out. Why?

后端 未结 5 2001
感动是毒
感动是毒 2021-02-12 03:58

I have tried a simple experiment to verify the functionality of the garbage collector. Referencing 3.9 Automatic memory management (MSDN) about automatic memory managem

5条回答
  •  野性不改
    2021-02-12 04:32

    Garbage collection is expensive. You only want it to run as seldom as possible. Ideally never. Therefore, the system will try delaying garbage collection as long as it can, basically until you run out of memory.

    Allocating memory is expensive. Once the runtime has allocated some memory, it will typically not free it again, even if it doesn't currently need it, because if it needed that much memory during one time of the runtime of the program, it is likely that it will need similar amounts of memory at some time in the future and wants to avoid having to allocate memory again.

    So, even if garbage collection occurred during your test, you wouldn't see it in the Task Manager or Process Explorer, because the CLR wouldn't free it anyway.

    What you are describing is called a reference-counting garbage collector. However, all currently existing implementations of the CLI VES use a tracing GC. Tracing GCs don't count references; they trace them, only when they are running. A tracing GC will not notice whether an object is still reachable or not until it actually traces the object graph, and it will only trace the object graph when it needs to run a collection, i.e. when you run out of memory.

提交回复
热议问题