1
votes

Every one knows - Garbage Collector cleans the memory from unused objects.

My question is, what is the parameters to define whether this object is unused or not?

2
There are none. However, you can influence how the GC treats objects using things like GC.KeepAlive or the C# fixed statement. Note that both don't prevent the actual collection from happening, but just alter certain behaviors (follow the links to find out more). - Christian.K

2 Answers

2
votes

The number of pointers to the object is zero => the object is unused (unreachable)

1
votes

The two major forms of garbage collection are Mark & Sweep, or reference counting.

Most modern day languages uses a combination or a variation of several methods. This will cover the general concept of each scheme.

Additionally, escape analysis is used to "reduce" the amount of "garbage".

Mark & Sweep

This works by having all object, with a single boolean "marked" parameter.

  1. It starts with marking all the objects within the memory space as "false".
  2. Starts from the top "global" object, and for each of its child, mark it as "true"
  3. For each of the subchild, mark them as "true". Repeat this step for each subchild that was originally "false". (Recursion)
  4. Finally delete all objects with "false". Repeat the process at 1 subsequently (possibly at a later time)

Reference Counting

This works on the concept of counting the amount of with an integer "parent references" parameter and deleting the object, when its count reaches zero.

  1. When an object/var is created and added to global/other objects. Its reference count is incremented by 1.
  2. When an object/var is removed from global/parent object. Its reference count is reduced by 1.
  3. If an object reference count is zero after removal. It is "Garbage Collected" as no one "owns it"

Escape Analysis

Is an additional method used to "reduce" the amount of garbage, by analysing your executing code. For temporary variables, that will never be "persistent" after a function execution. These objects/variables are then immediately cleared after your function execution. Avoiding the need of adding an object to the garbage collection system (in which will have an overhead). This step is critical in ensuring the performance of many modern day languages.

Detailed advantages / disadvantages of Mark & Sweep / Reference Counting can be found on wiki