Garbage Collection
I want to explain the Garbage Collection concept in C#.
Purpose: The definition of Garbage Collection is it will clear the memory space, the type of memory we can call the expired objects that are no longer needed.
Advantages
- Automatic memory management.
- Release managed and unmanaged resources and resource cleanup.
- Reduce the errors.s
- Prevent the memory leaks.
- Optimize the performance.
I would like to explain the Generations approach:
- GEN 0: Generation 0 represents short-lived objects, which are temporary objects, such as those used in methods, LINQ queries, etc.
If objects survive in Gen 0, they are moved to Gen 1. This generation is also referred to as the youngest generation.
- GEN 1: Generation 1 acts as an intermediate stage between short-lived (Gen 0) and long-lived (Gen 2) objects.
Examples include objects passed between methods, temporary configuration data, or state information that is reused across multiple operations.
- GEN 2: Generation 2 represents the long-lived objects. These objects have survived garbage collection in both GEN-0 and GEN-1.
Examples include database connection strings, dependency injection containers, singleton objects, etc. This generation represents the oldest generation in the garbage collection hierarchy.
Using Finalization and Dispose
Finalizers (~ClassName()): Allow objects to clean up resources before being collected. However, finalizers delay GC, so it's better to use IDisposable for resource management.
Differences between Finalise and Dispose
Finalise |
Dispose |
Finalize is called directly by the Garbage collector. |
The Dispose method has an IDispose Interface, and we must write a code for cleanup. |
It should only be used for the cleanup of unmanaged resources.
Unmanaged resources like file handles, database connections, or unmanaged memory that the garbage collector cannot clean up on its own. |
It should be used to clean up both managed and unmanaged resources.
Managed resources include objects, strings, collections, streams, and managed wrappers for unmanaged resources. |
It is less efficient because objects with finalizers take longer to be collected by the garbage collector, |
Generally, it is more efficient because it is called explicitly. |
Implemented by overriding the Object. Finalise method, usually by defining a destructor in C# (using the ~ClassName syntax). |
Implement the IDisposable interface and call Dispose explicitly or use a statement to ensure cleanup. |
It is called implicitly by the garbage collector, and it cannot be called directly by user code. |
It is called explicitly by the consumer of the class, typically using a statement or a try/finally block. |