rspec/rules/S1215/csharp/rule.adoc

32 lines
2.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2023-06-13 08:18:53 +02:00
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.
2020-06-30 12:47:33 +02:00
2023-06-13 08:18:53 +02:00
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.).
2021-02-02 15:02:10 +01:00
2023-06-13 08:18:53 +02:00
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.
2020-06-30 12:47:33 +02:00
2023-06-13 08:18:53 +02:00
This rule raises an issue when any overload of `Collect` is invoked.
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
static void Main(string[] args)
{
// ...
2023-06-13 08:18:53 +02:00
GC.Collect(); // Noncompliant
2020-06-30 12:47:33 +02:00
GC.Collect(2, GCCollectionMode.Optimized); // Noncompliant
}
----
2023-06-13 08:18:53 +02:00
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.
2023-06-13 08:18:53 +02:00
== Resources
2023-06-13 08:18:53 +02:00
=== Documentation
2023-06-13 08:18:53 +02:00
* 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]
2023-06-13 08:18:53 +02:00
include::rspecator.adoc[]