In this chapter, we are going to cover the conception of Garbage collection that is one most vital options of the .NET managed code platform. the Garbage collector (GC) manages the allocation and release of memory. the Garbage collector serves as an automatic memory manager.
- You do not need to know how to allot and release memory or manage the time period of the objects that use that memory
- An allocation is created any time you declare an object with a “new” keyword or a value type is boxed. Allocations are typically very fast
- When there have not enough memory to allot an object, the SC should collect and dispose garbage memory to create memory available for new allocations.
- This method is known as garbage collection.
Advantages of Garbage collection
Garbage Collection provides the following advantages −
- You don’t have to free memory manually while developing your application.
- It also allocates objects on the managed heap with efficiency.
- When objects aren’t any longer used then it’ll reclaim those objects by clearing their memory, and keeps the memory available for future allocations.
- Managed objects automatically get clean content to begin with, thus their constructors don’t have to initialize each information field.
- It also provides memory safety by ensuring that an object cannot use the content of another object.
Conditions for Garbage collection
Garbage collection happens when one of the following conditions is true.
- The system has low physical memory.
- The memory that’s used by allotted objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the method runs.
- The GC. Collect method is called and in most all cases, you do not have to call this method,because the garbage collector runs continuously. This method is primarily used for unique situation and testing.