DEV Community

Otávio Larrosa
Otávio Larrosa

Posted on

1 - A briefly understanding about Garbage collecting strategy in C#.

As a professional developer, constantly you need to improve your application performance. And in most of the cases, the first place you search is about database, or network usage, algorithm complexity and many other places a developer can see.
But, in some cases, the "villain" of the performance, is the garbage collector, when you're dealing with managed languages such as C#, Java, Python, Golang, and many other.

Well, here we have the benefits to use a managed language:

  1. You don't have to manually free the memory your program have allocated.
  2. The objects allocation on the managed heap is very efficient.
  3. Provides an automated way to release the memory.
  4. Make sure that an object will never access the memory allocated for another object(memory safety).

1 - How the CLR allocates memory?

When you initialize a program, the dotnet CLR(Common Language Runtime) reserves a contiguous address space for the process, this region is called "managed heap", imagine something like this:

Managed heap creation

Well, after creating the managed heap space, the CLR will set a pointer to next free block space on the memory, like this:

Managed heap set pointer

An important thing to mention, is that allocating memory in the managed heap, is faster than allocating memory in an unmanaged way, because the CLR has allocated and setted the pointer to the specific memory address. While the unmanaged way needs to search on the entire heap, a place that is enough to your variable/process/object.


2 - How the Garbage Collector runs?

The GC executes 4 steps all the times it was called:

Image description

  1. It suspends the execution of your program
  2. The GC sweeps all the managed heap, searching for objects that doesn't have more references to.
  3. The GC destroy this objects, move the remaining objects on the memory to the start of the managed heap spaces, and set the pointer to the next free space(here, the GC will promote the remaining objects from #gen0 to #gen1 and #gen2, but we will talk about this behaviour on the next post).
  4. The GC resumes the execution of your program.

3 - When the GC runs?

Nothing complex here, the garbage collector runs where one of these conditions is true:

  1. When the operating system or the host, notifies the CLR that the system has low memory available.
  2. When the memory used on the managed heap exceeds the acceptable threshold.
    2.1. Important thing to mention is: the acceptable memory threshold on managed heap is constantly adjusted while the process runs.

  3. When the GC.Collect method is arbitrary called by your code.
    3.1 Important thing: In most of the cases, you don't need to call this. And, is recommended to not use this call.

Top comments (0)