== Why is this an issue?

https://learn.microsoft.com/en-us/dotnet/api/system.gc.collect[GC.Collect] is a method that forces or suggests to the https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/[garbage collector] to run a collection of objects in the managed heap that are no longer being used and free their memory.

Calling `GC.Collect` is rarely necessary and can significantly affect application performance. That's because it is a https://en.wikipedia.org/wiki/Tracing_garbage_collection[tracing garbage collector] and needs to examine _every object in memory_ for cleanup and analyze all reachable objects from every application's root (static fields, local variables on thread stacks, etc.).

To perform tracing and memory releasing correctly, the garbage collection https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/latency[may] need to block all threads currently in execution. That is why, as a general rule, the https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/performance#troubleshoot-performance-issues[performance implications] of calling `GC.Collect` far outweigh the benefits.

This rule raises an issue when any overload of `Collect` is invoked.

[source,csharp]
----
static void Main(string[] args)
{
  // ...
  GC.Collect();                              // Noncompliant
  GC.Collect(2, GCCollectionMode.Optimized); // Noncompliant
}
----

There may be exceptions to this rule: for example, you've just triggered some event that is unique in the run of your program that caused a lot of long-lived objects to die, and you want to release their memory.

== Resources

=== Documentation

* https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/[Garbage collection]
* https://learn.microsoft.com/en-us/dotnet/api/system.gc.collect[GC.Collect]
* https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/latency[Garbage collection latency modes]
* https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/performance#troubleshoot-performance-issues[Garbage collection troubleshoot performance issues]

include::rspecator.adoc[]