A Garbage Collection (GC) is triggered for three main reasons, with the first being the most common.---

1. Allocations (The Main Trigger)

Most GCs are triggered by memory allocations.
The system uses an allocation budget, which you can think of as a trash can.

  • As your program runs and allocates memory (throws trash away), the can fills up.
  • Once the budget is spent (the can is full), a GC is automatically triggered to empty it and reclaim space.

Tip

Analogy: GC = emptying the trash can once it’s full.


2. High Physical Memory Pressure

A GC can also be triggered if the computer itself is running out of physical memory (RAM).

  • If the system detects that memory is low, it will trigger a GC in running processes.
  • This can happen even if their individual allocation budgets haven’t been met.

Warning

System-wide pressure can force GCs at inconvenient times, making performance less predictable.


3. Manual Calls

A developer can manually force a garbage collection by calling:

GC.Collect();
  • Generally not recommended for routine use.
  • Useful in diagnostic or special-case scenarios.

Note

Manual GC calls can sometimes help (e.g., after a large batch operation), but overusing them usually hurts performance.